198. House Robber

来源:互联网 发布:万网域名转让合同 编辑:程序博客网 时间:2024/05/25 01:36

Problem

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

DP问题, 用dp[ i ] 表示到  i 为止 (包含 i ) 的最大值,那么有两个选择

1)偷 i , 不偷 i -1    dp [ i - 2] + arr[ i ]

2) 不偷 i,  i -1 偷不偷都行   dp[ i - 1 ]


两者取最大 dp [ i ] = max (  dp [ i - 2] + arr[ i ], dp[ i - 1 ] );

class Solution {public:    int rob(vector<int>& nums) {        const int N = nums.size();        if(N == 0) return 0;        if(N == 1) return nums[0];                int num0 = nums[0], num1 = max(nums[0], nums[1]), num2 = num1;        for( int i = 2; i < N; i++){            num2 = max(num1, num0 + nums[i]);            num0 = num1;            num1 = num2;        }        return num2;    }};

  
0 0
原创粉丝点击