LeetCode OJ入门初探-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.

这个是讲一个盗贼不能连续偷两家,需要找到偷最大的效益。简单的说,就是说就是一个在数组中,找到不相隔的数的最大和。
思路:既然不能相隔,故可以设置三种状态数字,taken(这一次如果偷的话taken等于notaken + num[i]),notaken(确定这一次不偷,则仍然为之前的nowmax),nowmax(taken,notaken谁大选谁)。


class Solution {
public:
int rob(vector& nums) {
int taken = 0;
int notaken = 0;
int nowmax =0;
for(int i= 0; i < nums.size();i++) { taken = notaken +nums[i]; notaken = nowmax; //nowmax = Math.max(taken,notaken); if(taken > notaken)
nowmax = taken;
}
return nowmax;
}
};

LeetCode OJ入门初探-198. House Robber》上有3条评论

  1. Woah! I’m really enjoying the template/theme of this website.
    It’s simple, yet effective. A lot of times it’s difficult
    to get that “perfect balance” between superb usability and appearance.
    I must say you’ve done a awesome job with this. In addition, the blog loads extremely fast for me
    on Safari. Outstanding Blog!

发表评论