|
| 1 | +/** |
| 2 | + * [84] Largest Rectangle in Histogram |
| 3 | + * |
| 4 | + * 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. |
| 5 | + * |
| 6 | + * |
| 7 | + * |
| 8 | + * <img src="https://assets.leetcode.com/uploads/2018/10/12/histogram.png" style="width: 188px; height: 204px;" /><br /> |
| 9 | + * <small>Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].</small> |
| 10 | + * |
| 11 | + * |
| 12 | + * |
| 13 | + * <img src="https://assets.leetcode.com/uploads/2018/10/12/histogram_area.png" style="width: 188px; height: 204px;" /><br /> |
| 14 | + * <small>The largest rectangle is shown in the shaded area, which has area = 10 unit.</small> |
| 15 | + * |
| 16 | + * |
| 17 | + * |
| 18 | + * Example: |
| 19 | + * |
| 20 | + * |
| 21 | + * Input: [2,1,5,6,2,3] |
| 22 | + * Output: 10 |
| 23 | + * |
| 24 | + * |
| 25 | + */ |
| 26 | +pub struct Solution {} |
| 27 | + |
| 28 | +// submission codes start here |
| 29 | + |
| 30 | +// record the height and start position using 2 stack, thus we reuse the previously scanned information |
| 31 | +impl Solution { |
| 32 | + pub fn largest_rectangle_area(heights: Vec<i32>) -> i32 { |
| 33 | + let mut positions = Vec::new(); |
| 34 | + let mut hs = Vec::new(); |
| 35 | + let mut max_area = 0; |
| 36 | + let len = heights.len(); |
| 37 | + for (i, h) in heights.into_iter().enumerate() { |
| 38 | + let mut last_pop = None; |
| 39 | + while hs.last().is_some() && *hs.last().unwrap() >= h { |
| 40 | + max_area = i32::max(max_area, hs.last().unwrap() * ((i - positions.last().unwrap()) as i32)); |
| 41 | + hs.pop(); |
| 42 | + last_pop = positions.pop(); |
| 43 | + } |
| 44 | + if last_pop.is_some() { positions.push(last_pop.unwrap()); } else { positions.push(i); } |
| 45 | + hs.push(h); |
| 46 | + } |
| 47 | + // drain stack |
| 48 | + while !hs.is_empty() { |
| 49 | + max_area = i32::max(max_area, hs.last().unwrap() * ((len - positions.last().unwrap()) as i32)); |
| 50 | + positions.pop(); |
| 51 | + hs.pop(); |
| 52 | + } |
| 53 | + max_area |
| 54 | + } |
| 55 | +} |
| 56 | + |
| 57 | +// submission codes end |
| 58 | + |
| 59 | +#[cfg(test)] |
| 60 | +mod tests { |
| 61 | + use super::*; |
| 62 | + |
| 63 | + #[test] |
| 64 | + fn test_84() { |
| 65 | + assert_eq!(Solution::largest_rectangle_area(vec![2,1,5,6,2,3]), 10); |
| 66 | + assert_eq!(Solution::largest_rectangle_area(vec![1,1,1,1,1,1,1,1]), 8); |
| 67 | + assert_eq!(Solution::largest_rectangle_area(vec![2,2]), 4); |
| 68 | + assert_eq!(Solution::largest_rectangle_area(vec![1,2,8,8,2,2,1]), 16); |
| 69 | + assert_eq!(Solution::largest_rectangle_area(vec![2,1,2]), 3); |
| 70 | + assert_eq!(Solution::largest_rectangle_area(vec![1,3,2,1,2]), 5); |
| 71 | + } |
| 72 | +} |
0 commit comments