198. House Robber LeetCode

来源:互联网 发布:网络爬虫贴吧 编辑:程序博客网 时间:2024/05/17 20:30

题目描述:

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.

题目分析:这是一道简单题,主要是判断相邻地两家是否值得盗窃,以及如何选择。问题的症结就在可能选择盗取的那家旁边两家的价值要高于它,,这就存在选择的问题,我们可以设置两个变量用于存储盗与不盗这两种情况下的利益得失。我在本题之中设置了两个变量,a,b。a用于存储盗取nums[i]家的财物以及之前盗取的所有的财物价值之和,b就是不盗的情况。a,b的值保持同步。连续5家必选两家,4家必选一家。选择的优劣最多在达到5家的时候就可以分辨出来,这时候a,b同步为较大的那个。

代码:

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

0 0