-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathRainWaterTrapped.java
More file actions
89 lines (48 loc) · 1.25 KB
/
RainWaterTrapped.java
File metadata and controls
89 lines (48 loc) · 1.25 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
Problem Description
Given an integer array A of non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
Problem Constraints
1 <= |A| <= 100000
Input Format
The only argument given is integer array A.
Output Format
Return the total water it is able to trap after raining.
Example Input
Input 1:
A = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
Input 2:
A = [1, 2]
Example Output
Output 1:
6
Output 2:
0
Example Explanation
Explanation 1:
In this case, 6 units of rain water (blue section) are being trapped.
Explanation 2:
No water is trapped.
**/
public class Solution
{
// DO NOT MODIFY THE ARGUMENTS WITH "final" PREFIX. IT IS READ ONLY
public int trap(final int[] A)
{
int res = 0;
for(int i=1; i<A.length-1; i++)
{
int left = A[i];
for(int j=0; j<i; j++)
{
left = Math.max(A[j], left);
}
int right = A[i];
for(int j=i+1; j<A.length; j++)
{
right = Math.max(A[j], right);
}
res+=Math.min(left, right)- A[i];
}
return res;
}
}