198. House Robber

xiaoxiao2021-02-28  77

题目描述:

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); } };

转载请注明原文地址: https://www.6miu.com/read-84563.html

最新回复(0)