[LeetCode] House Robber

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.

这是一个动态规划问题,给定一个数组,找出不相邻的数字的最大和。

算法核心在于,如果抢劫第i个房屋,则cur money = 第i个房屋的money + 不抢劫第i - 1房屋时的money。如果不抢劫第i个房屋,则cur money = max(抢劫第i - 1房屋的money, 不抢劫第i - 1房屋的money)

class Solution {
public:
    int rob(vector<int>& nums) {
        int rob = 0; //  max money can get if rob current house.
        int notrob = 0; // max money can get if not rob current house.
        for (int i = 0; i != nums.size(); i++) {
            int currob = notrob + nums[i]; // if rob current house, previous must not be robbed.
            notrob = max(notrob, rob);  // if not rob this (ith) house, take the max value of robbed (i-i)th house and not robbed (i-1)th house.
            rob = currob; // update the rob value.
        }
        return max(rob, notrob); // return the max value after traversing the nums.  
    }
};
// 0 ms

 

posted @ 2017-08-23 17:13  immjc  阅读(121)  评论(0编辑  收藏  举报