-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTapping_RainWater.java
More file actions
67 lines (40 loc) · 1.18 KB
/
Tapping_RainWater.java
File metadata and controls
67 lines (40 loc) · 1.18 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
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
66
67
/*Given an array arr[] of N non-negative integers
* representing the height of blocks.
* If width of each block is 1,
* compute how much water can be trapped between
* the blocks during the rainy season. */
package java_ds_algo;
import java.util.*;
import java.util.Scanner;
public class Tapping_RainWater {
public static int trappedWater(int[] arr, int n) {
int left = 0;
int right = n - 1 ;
int total = 0;
for(int i =0;i < n-1 ;i++) {
int max_Left = arr[i];
for(int j = 0;j < i;j++) {
max_Left = Math.max(arr[j], max_Left);
}
int max_Right = arr[i];
for(int j = i+1;j < n;j++) {
max_Right = Math.max(arr[j], max_Right);
}
total = total + Math.min(max_Left, max_Right) - arr[i];
}
return total;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Enter array Size");
int n = sc.nextInt();
int[] arr = new int[n];
System.out.println("Enter Elements arry");
for(int i = 0;i < n;i++) {
arr[i] = sc.nextInt();
}
int ans = trappedWater(arr,n);
System.out.println("Trapped water units :"+ans);
}
}