-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
31 lines (28 loc) · 814 Bytes
/
Copy pathsolution.java
File metadata and controls
31 lines (28 loc) · 814 Bytes
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
class Solution {
public int maxWater(int arr[]) {
int n = arr.length;
if (n <= 2)
return 0;
int left = 0, right = n - 1;
int leftMax = 0, rightMax = 0;
int water = 0;
while (left < right) {
if (arr[left] < arr[right]) {
if (arr[left] >= leftMax) {
leftMax = arr[left];
} else {
water += leftMax - arr[left];
}
left++;
} else {
if (arr[right] >= rightMax) {
rightMax = arr[right];
} else {
water += rightMax - arr[right];
}
right--;
}
}
return water;
}
}