-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 0042_Trapping_Rain_Water.java
- Loading branch information
Showing
1 changed file
with
30 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
// id: 42 | ||
// Name: Trapping Rain Water | ||
// link: https://leetcode.com/problems/trapping-rain-water/description/ | ||
// Difficulty: Hard | ||
|
||
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; | ||
} | ||
} |