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++
kotlin
沒有留言:
張貼留言