Skip to content

Instantly share code, notes, and snippets.

@owengalenjones
Created October 4, 2018 19:19
Show Gist options
  • Save owengalenjones/ccbd7f734a53c1df5b7b3cd6452cd027 to your computer and use it in GitHub Desktop.
Save owengalenjones/ccbd7f734a53c1df5b7b3cd6452cd027 to your computer and use it in GitHub Desktop.
class Solution {
public int rob(int[] nums) {
if(nums.length == 0) { return 0; }
int takeA = nums[0], leaveA = 0, takeB = 0, leaveB = 0;
for(int i = 1; i < nums.length; i++) {
int tmpTakeA = takeA, tmpLeaveA = leaveA, tmpTakeB = takeB, tmpLeaveB = leaveB;
takeA = (i == nums.length - 1) ? 0 : tmpLeaveA + nums[i];
leaveA = Math.max(tmpTakeA, tmpLeaveA);
takeB = tmpLeaveB + nums[i];
leaveB = Math.max(tmpTakeB, tmpLeaveB);
}
return Math.max(Math.max(takeA, leaveA),
Math.max(takeB, leaveB));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment