New Problem "House Robber II"

This commit is contained in:
Hao Chen 2015-06-10 20:37:12 +08:00
parent 98ffa55553
commit 0b5710948d
2 changed files with 58 additions and 0 deletions

View File

@ -7,6 +7,7 @@ LeetCode
| # | Title | Solution | Difficulty |
|---| ----- | -------- | ---------- |
|197|[House Robber II](https://leetcode.com/problems/house-robber-ii/)| [C++](./algorithms/houseRobber/houseRobber.II.cpp)|Medium|
|196|[Word Search II](https://leetcode.com/problems/word-search-ii/)| [C++](./algorithms/wordSearch/wordSearch.II.cpp)|Hard|
|195|[Add and Search Word - Data structure design](https://leetcode.com/problems/add-and-search-word-data-structure-design/)| [C++](./algorithms/addAndSearchWord/AddAndSearchWord.cpp)|Medium|
|194|[Course Schedule II](https://leetcode.com/problems/course-schedule-ii/)| [C++](./algorithms/courseSchedule/CourseSchedule.II.cpp)|Medium|

View File

@ -0,0 +1,57 @@
// Source : https://leetcode.com/problems/house-robber-ii/
// Author : Hao Chen
// Date : 2015-06-10
/**********************************************************************************
*
* Note: This is an extension of House Robber.
*
* 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 are arranged 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.
*
**********************************************************************************/
class Solution {
public:
int orginal_rob(vector<int> &money, int start, int end) {
int n2=0;
int n1=0;
for (int i=start; i<end; i++){
int current = max(n1, n2 + money[i]);
n2 = n1;
n1 = current;
}
return n1;
}
int rob(vector<int>& nums) {
int n = nums.size();
switch (n) {
case 0:
return 0;
case 1:
return nums[0];
case 2:
return max(nums[0], nums[1]);
default:
/*
* the idea is we cannot rob[0] and rob[n-1] at same time
* so, we rob [0 .. n-2] or [1 .. n-1], can return the maxinum one.
*/
int m1 = orginal_rob(nums, 0, n-1);
int m2 = orginal_rob(nums, 1, n);
return max(m1, m2);
}
}
};