-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrapping_rain_water.rs
58 lines (54 loc) · 1.4 KB
/
trapping_rain_water.rs
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
///
/// Problem: Trapping Rain Water
///
/// Given an array `height` representing the elevation map where the width of each bar is `1`,
/// compute how much water can be trapped **after raining**.
///
/// **Example 1:**
/// ```plaintext
/// Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
/// Output: 6
/// ```
///
/// **Example 2:**
/// ```plaintext
/// Input: height = [4,2,0,3,2,5]
/// Output: 9
/// ```
///
/// **Constraints:**
/// - `1 <= height.length <= 10^5`
/// - `0 <= height[i] <= 10^4`
///
/// # Solution:
///
/// **Time Complexity:** `O(n)`
/// **Space Complexity:** `O(1)`
impl Solution {
pub fn trap(height: Vec<i32>) -> i32 {
if height.is_empty() {
return 0;
}
let (mut left, mut right) = (0, height.len() - 1);
let (mut left_max, mut right_max) = (0, 0);
let mut water = 0;
while left < right {
if height[left] < height[right] {
if height[left] >= left_max {
left_max = height[left];
} else {
water += left_max - height[left];
}
left += 1;
} else {
if height[right] >= right_max {
right_max = height[right];
} else {
water += right_max - height[right];
}
right -= 1;
}
}
water
}
}