fn largest_rectangle_area(heights: Vec<i32>) -> i32 {
let mut stack = Vec::new();
let mut max_area = 0;
let mut i = 0;
while i < heights.len() {
if stack.is_empty() || heights[i] >= heights[*stack.last().unwrap()] {
stack.push(i);
i += 1;
} else {
let top = stack.pop().unwrap();
let width = if stack.is_empty() { i as i32 } else { (i - stack.last().unwrap() - 1) as i32 };
let area = heights[top] * width;
if area > max_area {
max_area = area;
}
}
}
while !stack.is_empty() {
let top = stack.pop().unwrap();
let width = if stack.is_empty() { i as i32 } else { (i - stack.last().unwrap() - 1) as i32 };
let area = heights[top] * width;
if area > max_area {
max_area = area;
}
}
max_area
}
fn main() {
let histogram = vec![2, 1, 5, 6, 2, 3];
println!("{}", largest_rectangle_area(histogram));
}The largest rectangle area in the histogram [2, 1, 5, 6, 2, 3] is 10. This is formed by the bars with heights 5 and 6 (width 2), giving area 5*2=10.
The stack stores indices of bars in increasing height order. When a smaller bar is found, it means the rectangle with the height of the bar at the top of the stack ends there. This helps calculate the area efficiently.
fn largest_rectangle_area(heights: Vec<i32>) -> i32 {
let mut stack = Vec::new();
let mut max_area = 0;
let mut i = 0;
while i <= heights.len() {
let current_height = if i == heights.len() { 0 } else { heights[i] };
if stack.is_empty() || current_height >= heights[*stack.last().unwrap()] {
stack.push(i);
i += 1;
} else {
let top = stack.pop().unwrap();
let width = if stack.is_empty() { i as i32 } else { (i - stack.last().unwrap() - 1) as i32 };
let area = heights[top] * width;
if area > max_area {
max_area = area;
}
}
}
max_area
}
fn main() {
let histogram = vec![2, 1, 5, 6, 2, 3];
println!("{}", largest_rectangle_area(histogram));
}The code uses a sentinel height 0 at the end by checking if i == heights.len(), so it safely processes all bars and empties the stack. It outputs 10 without error.
fn largest_rectangle_area(heights: Vec<i32>) -> i32 {
let mut stack = Vec::new();
let mut max_area = 0;
let mut i = 0;
while i < heights.len() {
if stack.is_empty() || heights[i] >= heights[*stack.last().unwrap()] {
stack.push(i);
i += 1;
} else {
let top = stack.pop().unwrap();
let width = if stack.is_empty() { i as i32 } else { (i - stack.last().unwrap() - 1) as i32 };
let area = heights[top] * width;
if area > max_area {
max_area = area;
}
}
}
while !stack.is_empty() {
let top = stack.pop().unwrap();
let width = if stack.is_empty() { i as i32 } else { (i - stack.last().unwrap() - 1) as i32 };
let area = heights[top] * width;
if area > max_area {
max_area = area;
}
}
max_area
}
fn main() {
let histogram = vec![2, 2, 2, 2];
println!("{}", largest_rectangle_area(histogram));
}All bars have height 2 and there are 4 bars, so the largest rectangle area is 2 * 4 = 8.
By building histograms for each row and applying the largest rectangle algorithm, the maximum rectangle area of 1s in the matrix is 6.
