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.
题目大意是给你一个保存正数的数组,要你根据要求计算最大和(要求:每次不能选择相邻的两个数)
解题思路:DP问题。对于某个元素nums[i],是否并入和中主要有两点(sum1表示偶数下标的和,sum2表示奇数下标的和):
i为偶数:sum1 = max(sum1 + nums[i], sum2)
i为奇数:sum2 = max(sum2 + nums[i], sum1)
class Solution {
#define max(a,b) (a>b?a:b)
public:
int rob(vector<int>& nums) {
int sum1 = 0, sum2 = 0;
int count = nums.size();
if (0 == count)
{
return 0;
}
for (int i = 0; i < count; i++)
{
if (i % 2 == 0)
sum1 = max(sum1 + nums[i], sum2);
else
sum2 = max(sum2 + nums[i], sum1);
}
return max(sum1, sum2);
}
};