-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArraysecondpart.java
More file actions
37 lines (34 loc) · 1.12 KB
/
Arraysecondpart.java
File metadata and controls
37 lines (34 loc) · 1.12 KB
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
import java.util.*;
public class Arraysecondpart{
// trapping rain water
public static int trappedrainwater(int height[]){
int n = height.length;
// calculate maximum left boundary
int leftMax[] = new int[n]; //helper array
leftMax[0] = height[0];
for(int i =1;i<n;i++){
leftMax[i] = Math.max(height[i],leftMax[i-1]);
}
// calculate maximum left boundary
int rightmax[] = new int[n];
rightmax[n-1] = height[n-1];
for(int i = n-2;i>=0;i--){
rightmax[i]= Math.max(height[i],rightmax[i+1]);
}
int tp = 0;
// loop
for(int i=0;i<n;i++){
// water level
int waterlevel = Math.min(leftMax[i],rightmax[i]);
// trapped water
tp += waterlevel-height[i];
}
return tp;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
sc.close();
int height[] = {4,2,0,6,3,2,5};
System.out.println(trappedrainwater(height));
}
}