AlgoMaster Logo

Largest Rectangle in Histogram

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Brute Force

Intuition:

The simplest way to solve this problem is by considering each bar as the smallest (shortest) bar in the rectangle and expanding outwards. For each bar, we try to find the maximum possible rectangle by expanding to the left and right until we can no longer keep the height of that rectangle as the current bar.

Code:

2. Better Brute Force with Pruning

Intuition:

This builds on the idea of the simple brute force but introduces a pruning step by stopping earlier when the heights decrease and thus cannot extend the rectangle further in a beneficial way.

Code:

3. Using Stack (Optimal)

Intuition:

The most optimal solution involves using a stack to store indices of the histogram's bars. By utilizing a stack, we can ensure that we always process these histogram bars in an order where we have the necessary information to calculate the maximum rectangle as we proceed. When a lower height is encountered, we process and calculate areas for all bars taller than the current one by treating them as the smallest bar of their respective rectangles.

Code: