-
-
Notifications
You must be signed in to change notification settings - Fork 609
/
Copy pathHouseRober2.java
44 lines (32 loc) · 1.19 KB
/
HouseRober2.java
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
32
33
34
35
36
37
38
39
40
41
42
43
44
package problems.medium;
/**
* Created by rajat on 15/08/18.
*/
public class HouseRober2 {
public int rob(int[] nums) {
int totalHouses = nums.length;
if(totalHouses == 0) {
return 0;
}
if(totalHouses == 1) {
return nums[0];
}
int maxUptilPrevHouseIncludingFirst = nums[0];
int excludingPrevHouseIncludingFirst = 0;
int maxUptilPrevHouseExcludingFirst = nums[1];
int excludingPrevHouseExcludingFirst = 0;
for(int i=2;i<totalHouses;i++) {
int excludingThisHouse = maxUptilPrevHouseExcludingFirst;
int includeThisHouse = excludingPrevHouseExcludingFirst + nums[i];
maxUptilPrevHouseExcludingFirst = Math.max(includeThisHouse,excludingThisHouse);
excludingPrevHouseExcludingFirst = excludingThisHouse;
}
for(int i=1;i<totalHouses-1;i++) {
int excludingThisHouse = maxUptilPrevHouseIncludingFirst;
int includeThisHouse = excludingPrevHouseIncludingFirst + nums[i];
maxUptilPrevHouseIncludingFirst = Math.max(includeThisHouse,excludingThisHouse);
excludingPrevHouseIncludingFirst = excludingThisHouse;
}
return Math.max(maxUptilPrevHouseIncludingFirst,maxUptilPrevHouseExcludingFirst);
}
}