Skip to content

Commit

Permalink
Solve Two House Robber Problems
Browse files Browse the repository at this point in the history
  • Loading branch information
bky373 committed Jul 9, 2024
1 parent 56e12fd commit e1bc2d3
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
33 changes: 33 additions & 0 deletions house-robber-ii/bky373.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
time: O(N)
time: O(1)
*/
class Solution {

public int rob(int[] nums) {
if (nums.length == 0) {
return 0;
}
if (nums.length == 1) {
return nums[0];
}

return Math.max(
dp(nums, 0, nums.length - 2),
dp(nums, 1, nums.length - 1)
);
}

private static int dp(int[] nums, int start, int end) {
int maxOfOneStepAhead = nums[end];
int maxOfTwoStepsAhead = 0;

for (int i = end - 1; i >= start; --i) {
int curr = Math.max(maxOfOneStepAhead, maxOfTwoStepsAhead + nums[i]);

maxOfTwoStepsAhead = maxOfOneStepAhead;
maxOfOneStepAhead = curr;
}
return maxOfOneStepAhead;
}
}
23 changes: 23 additions & 0 deletions house-robber/bky373.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
time: O(N)
space: O(1)
*/
class Solution {

public int rob(int[] nums) {
if (nums.length == 0) {
return 0;
}

int maxOfTwoStepsAhead = 0;
int maxOfOneStepAhead = nums[nums.length - 1];

for (int i = nums.length - 2; i >= 0; --i) {
int curr = Math.max(maxOfOneStepAhead, maxOfTwoStepsAhead + nums[i]);

maxOfTwoStepsAhead = maxOfOneStepAhead;
maxOfOneStepAhead = curr;
}
return maxOfOneStepAhead;
}
}

0 comments on commit e1bc2d3

Please sign in to comment.