Skip to content

Commit fe213bb

Browse files
authored
Create House Robber II.java
1 parent 2d2b3d4 commit fe213bb

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

House Robber II.java

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
// https://leetcode.com/problems/house-robber-ii/
2+
3+
class Solution {
4+
5+
public int robbing(int[] houses, int startIdx, int endIdx) {
6+
7+
// OBJECTIVE: Iterate array linearly with 2 different iterators. Return the highest profitable iterator
8+
9+
// Add money from 1st house to 3rd house
10+
houses[2] += houses[startIdx];
11+
12+
// Iterate houses
13+
for (int i=3; i<endIdx; i++) {
14+
houses[i] += Math.max(houses[i - 2], houses[i - 3]);
15+
}
16+
17+
// Return the most profitable robbing spree
18+
return Math.max(houses[endIdx - 1], houses[endIdx - 2]);
19+
}
20+
21+
public void sliceArray(int[] source, int[] dest, int startIdx, int endIdx) {
22+
23+
// OBJECTIVE: Add elements from start to end to dest array
24+
25+
for (int i=startIdx; i<endIdx; i++) {
26+
dest[i] = source[i];
27+
}
28+
}
29+
30+
public int rob(int[] nums) {
31+
32+
// Get length of house
33+
int n = nums.length;
34+
35+
// If there are less than 4 houses, return the house with the most money
36+
// NOTE: Can't rob adjacent houses!
37+
if (n < 4) {
38+
39+
int maximumElem = 0;
40+
for (int i=0; i<n; i++) {
41+
maximumElem = Math.max(maximumElem, nums[i]);
42+
}
43+
44+
return maximumElem;
45+
}
46+
47+
// If there are exactly 4 houses, return the pair with the most money
48+
else if (n == 4) {
49+
return Math.max(nums[0] + nums[2], nums[1] + nums[3]);
50+
}
51+
52+
// Create 2 new arrays
53+
int[] sliceA = new int[n];
54+
int[] sliceB = new int[n];
55+
56+
// Slice nums[] and add elements to sliceA and sliceB
57+
sliceArray(nums, sliceA, 0, n - 1);
58+
sliceArray(nums, sliceB, 1, n);
59+
60+
// If there are more than 4 houses, return the most profitable robbing spree
61+
return Math.max(robbing(sliceA, 0, sliceA.length), robbing(sliceB, 0, sliceB.length));
62+
}
63+
}

0 commit comments

Comments
 (0)