forked from aylei/leetcode-rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathn0084_largest_rectangle_in_histogram.rs
72 lines (67 loc) · 2.37 KB
/
n0084_largest_rectangle_in_histogram.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/**
* [84] Largest Rectangle in Histogram
*
* Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
*
*
*
* <img src="https://assets.leetcode.com/uploads/2018/10/12/histogram.png" style="width: 188px; height: 204px;" /><br />
* <small>Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].</small>
*
*
*
* <img src="https://assets.leetcode.com/uploads/2018/10/12/histogram_area.png" style="width: 188px; height: 204px;" /><br />
* <small>The largest rectangle is shown in the shaded area, which has area = 10 unit.</small>
*
*
*
* Example:
*
*
* Input: [2,1,5,6,2,3]
* Output: 10
*
*
*/
pub struct Solution {}
// submission codes start here
// record the height and start position using 2 stack, thus we reuse the previously scanned information
impl Solution {
pub fn largest_rectangle_area(heights: Vec<i32>) -> i32 {
let mut positions = Vec::new();
let mut hs = Vec::new();
let mut max_area = 0;
let len = heights.len();
for (i, h) in heights.into_iter().enumerate() {
let mut last_pop = None;
while hs.last().is_some() && *hs.last().unwrap() >= h {
max_area = i32::max(max_area, hs.last().unwrap() * ((i - positions.last().unwrap()) as i32));
hs.pop();
last_pop = positions.pop();
}
if last_pop.is_some() { positions.push(last_pop.unwrap()); } else { positions.push(i); }
hs.push(h);
}
// drain stack
while !hs.is_empty() {
max_area = i32::max(max_area, hs.last().unwrap() * ((len - positions.last().unwrap()) as i32));
positions.pop();
hs.pop();
}
max_area
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_84() {
assert_eq!(Solution::largest_rectangle_area(vec![2,1,5,6,2,3]), 10);
assert_eq!(Solution::largest_rectangle_area(vec![1,1,1,1,1,1,1,1]), 8);
assert_eq!(Solution::largest_rectangle_area(vec![2,2]), 4);
assert_eq!(Solution::largest_rectangle_area(vec![1,2,8,8,2,2,1]), 16);
assert_eq!(Solution::largest_rectangle_area(vec![2,1,2]), 3);
assert_eq!(Solution::largest_rectangle_area(vec![1,3,2,1,2]), 5);
}
}