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.
<Solution>這題直接用個例子來說明,假設題目給的 array 是 nums = [2,3,7,1,4,5]
- 用 DP 來解這題,dp[i] 代表在 i 位置時,最多能偷到多少錢
- dp[0] = nums[0];因為也只能偷這家
- dp[1] = max(nums[0], nums[1]);在 i = 1 時,偷 0 和 1 中,錢多的那家
- dp[2] = max(dp[0] + nums[2], dp[1]);在 i = 2 時,偷 2 的錢並加上 dp[0] (不會通知警察),和不偷2,偷 1 就好的錢,誰比較多
- 推導出公式,dp[i] = max(dp[i-2] + nums[i], dp[i-1])
c++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int rob(vector<int>& nums) { | |
if(nums.size() < 2) { | |
return nums.empty() ? 0 : nums[0]; | |
} | |
const int len = nums.size(); | |
vector<int> dp(len); | |
dp[0] = nums[0]; | |
dp[1] = max(nums[0], nums[1]); | |
for(int i = 2; i < len; i++) { | |
dp[i] = max(dp[i-2] + nums[i], dp[i-1]); | |
} | |
return dp.back(); | |
} | |
}; |
kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
fun rob(nums: IntArray): Int { | |
val dp = IntArray(nums.size) {0} | |
dp[0] = nums[0] | |
for(i in 1..nums.lastIndex) { | |
if (i > 1) { | |
dp[i] = Math.max(dp[i-1], nums[i] + dp[i-2]) | |
} else { | |
dp[i] = Math.max(nums[i], dp[i-1]) | |
} | |
} | |
return dp[nums.lastIndex] | |
} | |
} |
沒有留言:
張貼留言