LeetCode-213. House Robber II

网友投稿 254 2022-09-15

LeetCode-213. House Robber II

You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, 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.

Example 1:

Input: [2,3,2]Output: 3Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses.

Example 2:

Input: [1,2,3,1]Output: 4Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4.

题解:

分别对0 - n-2 和 1 - n-1两次搜索即可。

class Solution {public: int rob(vector& nums) { int n = nums.size(); if (n == 0) { return 0; } // 0 - n-2 int pre1 = nums[0], pre2 = 0, dp = nums[0]; for (int i = 1; i < n - 1; i++) { dp = max(pre2 + nums[i], pre1); pre2 = pre1; pre1 = dp; } int a = dp; pre1 = 0; pre2 = 0; // 1 - n-1 for (int i = 1; i < n; i++) { dp = max(pre2 + nums[i], pre1); pre2 = pre1; pre1 = dp; } return max(a, dp); }};

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:最简单片机可执行KNN算法
下一篇:华为-求小球落地5次后所经历的路程和第5次反弹的高度
相关文章

 发表评论

暂时没有评论,来抢沙发吧~