1693. Ring Skyline Rectangle

Medium3.5 points estimatedMonotonic StackStackArray

Bars of a circular fence stand around a plaza; heights[i] is the height of bar i, and bar n-1 is next to bar 0. A banner may be hung across any run of 1 to n bars that are consecutive around the circle (the run may wrap past the end of the array, and no bar is used twice). The banner is as tall as the shortest bar in its run, so its area is that height times the number of bars. Return the largest possible area as a long. Heights may be 0. Aim for O(n) time and O(n) space by sweeping a monotonic stack over the array written twice and capping every width at n.

Example 1

Input:
heights = [3,1,3]
Output:
6
Explanation:

The two 3s are neighbours around the circle, so the run of length 2 at height 3 has area 6, which beats the full ring (3) and any single bar.

Example 2

Input:
heights = [4,0,4,4]
Output:
12
Explanation:

The run that wraps from the last two bars to the first has three bars of height 4 and area 12; the 0 bar is left out.

Example 3

Input:
heights = [2,2,2]
Output:
6
Explanation:

All three bars can be used together, area 2 * 3 = 6.

Constraints

1 ≤ heights.length ≤ 105

0 ≤ heights[i] ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…