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.
强盗进入房子盗窃,且不能进入两相邻的房间盗窃,求最大利益。
即在一个数组里选若干个数,选中的数不能相邻,求它们最大的和。
动态规划。
MAX[i]为到第i间房子的最大利润。
MAX[i] = max(MAX[i - 2] + nums[i] , MAX[i - 1])
class Solution { public: int rob(vector<int>& nums) { int n = nums.size(); vector<int>MAX(n,0); if (n == 0) return 0; if (n == 1) return nums[0]; MAX[0] = nums[0]; MAX[1] = max(MAX[0],nums[1]); for (int i = 2;i < n;i++) { MAX[i] = max(MAX[i -2] + nums[i],MAX[i - 1]); } return MAX[n - 1]; } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/u014705854/article/details/47123535