Skip to content

Instantly share code, notes, and snippets.

@junjiah
Last active August 29, 2015 14:25
Show Gist options
  • Save junjiah/a113e811c6821d8404f3 to your computer and use it in GitHub Desktop.
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/
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