198. House Robber
Leetcode
https://leetcode.com/problems/house-robber/description/
題目
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 systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
Example 1:
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.Example 2:
Input: nums = [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.解答
方法 1 - DP
範例:nums = [2,7,9,3,1]
當 i = 0 時,最多能偷的錢為 2
當 i = 1 時,最多能偷的錢為 7
當 i = 2 時,最多能偷的錢為 11 (2+9)
當 i = 3 時,最多能偷的錢為 11 (2+9)
當 i = 4 時,最多能偷的錢為 12 (2+9+1)
觀察上面規律可以發現,到第 i 天為止,能夠最多偷到錢的可能有以下兩種:
第 i - 2 天能偷到的最多錢 + 第 i 天偷的錢
第 i - 1 天能偷到的最多錢
接著只要判斷 1. 及 2. 的方式哪一個偷到的錢最多,一直去更新 DP 就好
var rob = function (nums) {
const dp = [nums[0]];
let max = nums[0];
for (let i = 1; i < nums.length; i++) {
const value = nums[i];
if (i === 1) {
dp[i] = Math.max(nums[0], nums[1]);
} else {
// 1. dp[i - 2] + value
// 2. dp[i - 1]
dp[i] = Math.max(dp[i - 2] + value, dp[i - 1]);
}
max = Math.max(max, dp[i]);
}
return max;
};參考資料
Last updated
Was this helpful?