[leetcode] House Robber

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.

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

Have you met this question in a real interview?
 
分析:DP算法,状态转移公式为: best[i] = max( best[i-2] + nums[i], best[i-1]);
 
class Solution
{
public:
  int rob(vector<int> &nums)
  {
    if(nums.empty()) return 0;
    if(nums.size() == 1) return nums[0];

    int size = nums.size();
    int pre_best = nums[0];
    int best = max(nums[1], nums[0]);

    for(int i=2; i < size; i++)
    {
      int temp = best;
      best = max(pre_best + nums[i], best);
      pre_best = temp;
    }

    return best;
  }
};
原文地址:https://www.cnblogs.com/lxd2502/p/4488046.html