Last active
August 29, 2015 14:25
-
-
Save junjiah/a113e811c6821d8404f3 to your computer and use it in GitHub Desktop.
solved 'House Robber II' on leetcode https://leetcode.com/problems/house-robber-ii/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
int rob(vector<int>& nums) { | |
int nums_len = nums.size(); | |
if (nums_len == 0) { | |
return 0; | |
} | |
else if (nums_len == 1) { | |
return nums[0]; | |
} | |
// Fix choosing the first place. | |
int max_prev_prev = nums[0], | |
max_prev = nums[0]; | |
// The last place cannot be chosen! | |
for (int i = 2; i < nums_len - 1; ++i) { | |
int max_curr = max(max_prev_prev + nums[i], max_prev); | |
max_prev_prev = max_prev; | |
max_prev = max_curr; | |
} | |
int max_to_rub_fix_first = max(max_prev_prev, max_prev); | |
// Another round, fix the second space. | |
max_prev_prev = 0; | |
max_prev = nums[1]; | |
// It's fine to choose the last place in this case. | |
for (int i = 2; i < nums_len; ++i) { | |
int max_curr = max(max_prev_prev + nums[i], max_prev); | |
max_prev_prev = max_prev; | |
max_prev = max_curr; | |
} | |
int max_to_rub_fix_second = max(max_prev_prev, max_prev); | |
return max(max_to_rub_fix_first, max_to_rub_fix_second); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment