-
Notifications
You must be signed in to change notification settings - Fork 37
/
42 Trapping Rain Water
65 lines (50 loc) · 1.56 KB
/
42 Trapping Rain Water
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
Brute Force
public int trap(int[] height) {
int n = height.length;
int[] leftMax = new int[n];
int[] rightMax = new int[n];
int max = 0;
int totalwater = 0;
for(int i=0;i<n;i++){
max = Math.max(max,height[i]);
leftMax[i] = max;
}
max = 0;
for(int i=n-1;i>=0;i--){
max = Math.max(max,height[i]);
rightMax[i] = max;
}
for(int i=n-1;i>=0;i--){
int water = Math.min(leftMax[i],rightMax[i])-height[i];
totalwater += water;
}
return totalwater;
}
---------************** Optimal Code **************--------------
public int trap(int[] height) {
int n = height.length;
int totalwater = 0;
int max = 0;
int maxIndex = 0;
for(int i=0;i<n;i++){
if(height[i]>max){
max = height[i]; //rmax
maxIndex = i;
}
}
int leftMax = 0;
//part1
for(int i=0;i<maxIndex;i++){
leftMax = Math.max(leftMax,height[i]);
int water = Math.min(leftMax,max)-height[i];
totalwater += water;
}
leftMax = 0;
//part2
for(int i=n-1;i>maxIndex;i--){
leftMax = Math.max(leftMax,height[i]);
int water = Math.min(leftMax,max)-height[i];
totalwater += water;
}
return totalwater;
}