1. 程式人生 > 實用技巧 >斐波那契_198. 打家劫舍

斐波那契_198. 打家劫舍

你是一個專業的小偷,計劃偷竊沿街的房屋。每間房內都藏有一定的現金,影響你偷竊的唯一制約因素就是相鄰的房屋裝有相互連通的防盜系統,如果兩間相鄰的房屋在同一晚上被小偷闖入,系統會自動報警。

給定一個代表每個房屋存放金額的非負整數陣列,計算你 不觸動警報裝置的情況下 ,一夜之內能夠偷竊到的最高金額。

示例 1:

輸入:[1,2,3,1]
輸出:4
解釋:偷竊 1 號房屋 (金額 = 1) ,然後偷竊 3 號房屋 (金額 = 3)。
  偷竊到的最高金額 = 1 + 3 = 4 

示例 2:

輸入:[2,7,9,3,1]
輸出:12
解釋:偷竊 1 號房屋 (金額 = 2), 偷竊 3 號房屋 (金額 = 9),接著偷竊 5 號房屋 (金額 = 1)。
  偷竊到的最高金額 
= 2 + 9 + 1 = 12 。

提示:

  • 0 <= nums.length <= 100
  • 0 <= nums[i] <= 400

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/house-robber


思路:

和斐波那契的的規則類似,只不過這次要先儲存的是nums陣列後的最大值

class Solution {
    public static int rob(int[] nums) {
        int money = 0;
        int money2 = 0;
        int len = nums.length;
        
for (int i = 0; i < nums.length; i++) { int cur = Math.max(money + nums[i], money2); money = money2; money2 = cur; } return money2; } }