Largest Histogram Rectangle

Write the code, see it run, pass the checks.

The problem

  • hard
  • Code
  • Pro

Write largestRectangle(heights): heights describes a bar chart whose bars are each 1 wide and stand side by side, with whole-number heights from 0 up. Return the area of the largest rectangle that fits inside the bars: it spans neighbouring bars and is as tall as the shortest of them. Return 0 when there are no bars. Don't change heights. For example, largestRectangle([2, 1, 5, 6, 2, 3]) is 10, from the bars of 5 and 6: 5 tall and 2 wide. The checks include 100,000 bars, so trying every pair of ends is too slow.

Your code must pass

  • Finds the largest rectangle
  • Uses one tall bar when that's best
  • Handles equal heights and zeros
  • Handles rising and falling bars
  • Is fast enough for 100,000 bars