AlgoDaily

Max Rectangle in a Histogram

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Description

We're given a histogram like the following, where contiguous (sharing a common border or touching) bars are made up of different heights. Let's assume all bars have the same width.

The histogram is converted to an array of the heights of the bars:

const histArr = [3, 1, 4, 2, 2, 1]

With this knowledge, can we find the largest rectangular area within the histogram? For the above, it would be the area outlined below:

With the above histogram, calling maxRectInHist(histArr) would get us 6. Can you fill in the method?

Constraints
  • Length of the array <= 100000
  • The array can be empty
  • The array will contain values between 1 and 10000
  • The final answer will always fit in the integer range
  • Expected time complexity : O(n)
  • Expected space complexity : O(n)
```js
const histArr = [3, 1, 4, 2, 2, 1];

function maxRectInHist(histArr) {
  // Fill in this method
  return histArr;
}

console.log(maxRectInHist(histArr));
```

CONTINUE WITH ALGODAILY PREMIUM

Keep going with the complete tutorial.

Unlock the remaining explanations and exercises, alongside the full learning library.

Explore Premium →
Open interactive view →