[LeetCode] House Robber 求数组中元素两两不相邻的子序列最大和

声明:原题目转载自LeetCode,解答部分为原创

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:
    思路:按照题意,给定一个数组array[ ],要求的是满足“元素两两不相邻”的子序列的最大和。假定函数f(k)代表以第k个元素array[k]结尾的满足该条件的子序列的最大和。
    我们可以很容易得出一个结论,目标子序列中两个相邻元素在原数组array[ ]中的位置要么间隔1位,要么间隔两位。因为当间隔3位时,肯定可以将中间位加到子序列中,从而获得更大和(间隔3位以上同理)。可以得出,状态转换方程为 
    f(k)= array[ k ] + max(  f(k - 1), f(k - 2));
   穷举所有的 f(k),其最大值即为目标子序列的最大和。
   代码如下:
class Solution {
public:
    int rob(vector& nums) {
        if(nums.size() == 0)
            return 0;
        if(nums.size() == 1)
            return nums[0];
        if(nums.size() == 2)
            return max(nums[0], nums[1]);
        if(nums.size() == 3)
            return max(nums[0] + nums[2], nums[1]);
            
        vector max_money(nums.size());
        max_money[0] = nums[0];
        max_money[1] = nums[1];
        max_money[2] = max(nums[0] + nums[2], nums[1]);
        int result = max( max(max_money[0], max_money[1]), max_money[2] );
        for(int i = 3; i < nums.size(); i ++)
        {
            max_money[i] = nums[i] + max(max_money[i - 2], max_money[i - 3]);
            result = max(result, max_money[i]);
        }
        return result;
    }
};


     

你可能感兴趣的:(LeetCode)