Leetcode: House Robber

来源:互联网 发布:java中类和对象的关系 编辑:程序博客网 时间:2024/06/15 08:28


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 andit 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 tonightwithout alerting the police.

比较简单的DP题。不能同时取相邻的房子,那么到当前房子最大的值取决于它前3,前2的房子值,从中选择大的即可。

class Solution {public:    int rob(vector<int>& nums) {        int max1 = 0;        int max2 = 0;        int max3 = 0;        for (int i = 0; i < nums.size(); ++i) {            int curMax = max(max1, max2) + nums[i];            max1 = max2;            max2 = max3;            max3 = curMax;        }                return max(max2, max3);    }};

0 0
原创粉丝点击