198. House Robber\max_element

198. 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.

这道题目就是把根据某种规则,对一个数组进行选取元素累加,求得其最大值。这个规则就是相邻的选取元素不能含有相邻的元素。比如v = [1,7,1,8,9,0,9,0] 不能同时选取第4、5个元素。

代码实现

这道题目很明显使用的是DP,我用了一个数组存了到该元素的最大和。在计算每个元素最大和的时候,我会比较是否大于之前保留需要返回的结果,如果是就更新准备返回的值。下面的第一份代码是使用了暴力破解的方法实现。后面的是DP。

class Solution {
public:
    int rob(vector<int>& nums) {
        int nlen = nums.size(), res = 0;
        vector<int> ttl(nlen, 0);
        for(int i = 0; i < nlen; i++) {
            if(i >= 2)  ttl[i] = *std::max_element(ttl.begin(), ttl.begin()+i-1) + nums[i];
            else ttl[i] = nums[i];
            if(res < ttl[i]) res = ttl[i];
        }
        return res;
    }
};

当然这个代码还可以简写成:

class Solution {
public:
    int rob(vector<int>& nums) {
        int nlen = nums.size();
        vector<int> ttl(nlen, 0);
        for(int i = 0; i < nlen; i++) {
            if(i >= 2)  ttl[i] = *std::max_element(ttl.begin(), ttl.begin()+i-1) + nums[i];
            else ttl[i] = nums[i];
        }
        return nlen?*std::max_element(ttl.begin(), ttl.end()):0;
    }
};

进一步看它的规律,发现前面的最大值部分可以在前一个或者两个地方。所以这道题目就是:

class Solution {
public:
    int rob(vector<int>& nums) {
        const int n = nums.size();
        if (n == 0) return 0;
        if (n == 1) return nums[0];
        if (n == 2) return max(nums[0], nums[1]);
        vector<int> f(n, 0);
        f[0] = nums[0];
        f[1] = max(nums[0], nums[1]);
        for (int i = 2; i < n; ++i)
            f[i] = max(f[i-2] + nums[i], f[i-1]);
        return f[n-1];
    }
};

参考:
【1】max_element: http://www.cplusplus.com/reference/algorithm/max_element/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值