Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit c1734a1

Browse files
solves house robber ii
1 parent 32a62a1 commit c1734a1

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@
172172
| 209 | [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum) | [![Java](assets/java.png)](src/MinimumSizeSubarraySum.java) | |
173173
| 210 | [Course Schedule II](https://leetcode.com/problems/course-schedule-ii) | [![Java](assets/java.png)](src/CourseScheduleII.java) | |
174174
| 211 | [Design Add and Search Words Data Structure](https://leetcode.com/problems/design-add-and-search-words-data-structure) | [![Java](assets/java.png)](src/DesignAddAndSearchWordsDataStructure.java) | |
175-
| 213 | [House Robber II](https://leetcode.com/problems/house-robber-ii) | | |
175+
| 213 | [House Robber II](https://leetcode.com/problems/house-robber-ii) | [![Java](assets/java.png)](src/HouseRobberII.java) | |
176176
| 215 | [Kth Largest Element in an Array](https://leetcode.com/problems/kth-largest-element-in-an-array) | [![Java](assets/java.png)](src/KthLargestElementInAnArray.java) | |
177177
| 216 | [Combination Sum III](https://leetcode.com/problems/combination-sum-iii) | | |
178178
| 217 | [Contains Duplicate](https://leetcode.com/problems/contains-duplicate) | [![Java](assets/java.png)](src/ContainsDuplicate.java) [![Python](assets/python.png)](python/contains_duplicate.py) | |

src/HouseRobberII.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// https://leetcode.com/problems/house-robber-ii
2+
// T: O(N)
3+
// S: O(1)
4+
5+
public class HouseRobberII {
6+
public int rob(int[] array) {
7+
if (array.length == 1) return array[0];
8+
if (array.length == 2) return Math.max(array[0], array[1]);
9+
10+
return Math.max(
11+
rob(array, 0, array.length - 2),
12+
rob(array, 1, array.length - 1)
13+
);
14+
}
15+
16+
public int rob(int[] array, int start, int end) {
17+
int a = array[start], b = Math.max(array[start], array[start + 1]), c = Math.max(a, b);
18+
for (int i = start + 2 ; i <= end ; i++) {
19+
c = Math.max(array[i] + a, b);
20+
a = b;
21+
b = c;
22+
}
23+
return c;
24+
}
25+
}

0 commit comments

Comments
 (0)