Largest Rectangular Panel Under a Row of Fence Posts

Implement largestFencePanelArea

A row of fence posts stands side by side, each with a given heights[i]. You want to nail up the widest possible rectangular banner that fits entirely under the tops of a contiguous run of posts — its height limited by the shortest post it spans. Given heights, return the largest possible banner area. Checking every contiguous run of posts directly costs O(n²). The key insight for going faster: instead of asking "what's the shortest post in this run?" for every possible run, ask the reverse question for each post individually — "how far left and right can a rectangle at this exact height extend before hitting something shorter?" A monotonic stack of post indices, kept in strictly increasing height order, answers that in a single left-to-right pass: whenever a shorter post appears, every taller post still on the stack has just found its right boundary, and its left boundary is whatever remains below it on the stack — so its rectangle can be finalized and popped, once, forever. Appending one sentinel post of height 0 at the very end guarantees every remaining post gets flushed and finalized too.

Example 1:

Input: heights = [6,4,7,3,5]

Output: 15

Example 2:

Input: heights = [2,4,2,1,10,6,10]

Output: 18

Example 3:

Input: heights = [1,8,6,2,5,4,8,3,7]

Output: 16

+ 4 hidden test cases run on Submit.

Constraints:

  • 1 ≤ heights.length ≤ 12
  • 0 ≤ heights[i] ≤ 100
  • The answer fits comfortably in a 32-bit signed integer for this input size

heights =

[6, 4, 7, 3, 5]