[LeetCode] House Robber II


After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place arearranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

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.

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

https://leetcode.com/problems/house-robber-ii/

 

LeetCode這是一天一道題的節奏嗎?這道題就是在上一題的基礎上加了一個條件,變成了環,所以如果搶了第一家,就不能搶最后一家。所以我們可以分別計算搶了從第二家到最后一家與搶從第一家到倒數第二家的最大值,取兩個值中更大的那個就是結果。

 1 class Solution {
 2 public:
 3     int rob(vector<int> &num) {
 4         if (num.size() == 0) return 0;
 5         if (num.size() == 1) return num[0];
 6         vector<int> dp(num.size());
 7         //搶第一家到倒數第二家的最大值
 8         dp[0] = num[0];
 9         for (int i = 1; i < num.size() - 1; ++i)
10             dp[i] = max(dp[i-1], (i == 1 ? 0 : dp[i-2]) + num[i]);
11         int res = dp[num.size()-2];
12         //搶第二家到最后一家的最大值
13         dp[1] = num[1];
14         for (int i = 2; i < num.size() ; ++i)
15             dp[i] = max(dp[i-1], (i == 2 ? 0 : dp[i-2]) + num[i]);
16         //返回兩者較大的一個    
17         return max(res, dp[num.size()-1]);
18     }
19 };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM