leetcode 198 House Robber

題目詳情

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.

題目的意思是,咱們是一個江洋大盜~如今咱們要去偷整條街的房子,每一個房子裏有必定的錢。可是任何臨近的兩個房子被偷就會觸發警報。要求咱們求出在不觸發警報的狀況下偷到的最多的錢。每一個房子裏的錢經過輸入的int數組表示。數組

想法

  • 動態規劃問題
  • 對於每個房子,咱們有偷/不偷兩種選擇
  • 所以咱們聲明兩個變量prevNo和prevYes分別保存,我沒偷/偷了當前房子的狀況下,目前爲止偷的最多的錢數。
  • 若是想偷當前房子,那麼要求咱們並無偷前一個房子,因此用前一個房子的prevNo值和當前房子的錢數相加。
  • 若是不偷當前房子,那咱們能夠取前一個房子的prevNo值和prevYes值中較大的那個。

解法

public int rob(int[] nums) {
                int prevNo = 0;
        int prevYes = 0;
        
        for(int n: nums){
            int temp = prevNo;
            prevNo = Math.max(prevNo, prevYes);
            prevYes = temp+n;
        }
        
        return Math.max(prevNo, prevYes);
    }
相關文章
相關標籤/搜索