-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0042_Trapping_Rain_Water.java
36 lines (29 loc) · 1.01 KB
/
0042_Trapping_Rain_Water.java
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
/*
* 42. Trapping Rain Water
* Problem Link: https://leetcode.com/problems/trapping-rain-water/description/
* Difficulty: Hard
*
* Solution Created by: Muhammad Khuzaima Umair
* LeetCode : https://leetcode.com/mkhuzaima/
* Github : https://github.com/mkhuzaima
* LinkedIn : https://www.linkedin.com/in/mkhuzaima/
*/
class Solution {
public int trap(int[] height) {
int n = height.length;
int [] rightMaxes = new int[n]; // maximum height at right of index i
rightMaxes[n-1] = 0; // no element right
for (int i = n-2; i >= 0; i--) {
rightMaxes[i] = Math.max(height[i+1], rightMaxes[i+1]);
}
int result = 0;
int leftMax = height[0];
for (int i = 1; i < height.length-1; i++) {
// max right, max left
int current = Math.min(rightMaxes[i], leftMax) - height[i];
if (current > 0) result += current;
leftMax = Math.max(leftMax, height[i]);
}
return result;
}
}