-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHouseRobber2.java
More file actions
31 lines (25 loc) · 849 Bytes
/
HouseRobber2.java
File metadata and controls
31 lines (25 loc) · 849 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package dynamic_programming;
/**
* Description: https://leetcode.com/problems/house-robber-ii
* Difficulty: Medium
* Time complexity: O(n)
* Space complexity: O(1)
*/
public class HouseRobber2 {
public int rob(int[] houses) {
if (houses.length < 2) return houses[0];
return Math.max(
rob(houses, 0, houses.length - 1), // skip last house
rob(houses, 1, houses.length)); // skip first house
}
private int rob(int[] houses, int from, int to) {
int adjacentRobbery = 0;
int prevPossibleRobbery = 0;
for (int i = from; i < to; i++) {
int tmp = adjacentRobbery;
adjacentRobbery = Math.max(adjacentRobbery, prevPossibleRobbery + houses[i]);
prevPossibleRobbery = tmp;
}
return adjacentRobbery;
}
}