198. House Robber

来源:互联网 发布:怎么看淘宝商品的类目 编辑:程序博客网 时间:2024/06/10 04:50

题目描述:

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.

解题思路:

为了不触动报警装置,我们必须间隔着房屋进行抢劫,也就是不能连续进行抢劫,所以我们在每一间房屋都要进行判断,选择金额最大的方案。

代码:

class Solution {public:    int rob(vector<int>& nums) {        int a = 0, b = 0;        for (int i = 0; i < nums.size(); i++) {            if (i%2 == 0) {                a = max(a+nums[i], b);            }            else {                b = max(a, b+nums[i]);            }        }        return max(a, b);    }};


0 0
原创粉丝点击