Alle Herausforderungen
Schwierig 0 gelöst 0% Erfolgsquote

Largest Rectangle in a Histogram

Find the largest rectangle that fits under a histogram.

Problem

A histogram has bars of width 1 with the given heights. Find the area of the largest rectangle that lies entirely within the bars. A monotonic stack gives an O(n) solution.

Implement largest_rectangle(heights).

Input

heights: Bar heights from left to right.

Output

Return the largest area.

Einschränkungen

0 ≤ length ≤ 200,000; 0 ≤ height ≤ 1,000,000,000

Beispiele

Beispiel 1
Eingabe:
heights = [2, 1, 5, 6, 2, 3]

Erwartete Ausgabe:
expected = 10
Eingabe:
std::vector<long long> heights = {2, 1, 5, 6, 2, 3};

Erwartete Ausgabe:
long long expected = 10;
Eingabe:
long[] heights = new long[] {2, 1, 5, 6, 2, 3};

Erwartete Ausgabe:
long expected = 10;

Erläuterung

Bars 5 and 6 together give a 2-wide rectangle of height 5: area 10.

Beispiel 2
Eingabe:
heights = [4]

Erwartete Ausgabe:
expected = 4
Eingabe:
std::vector<long long> heights = {4};

Erwartete Ausgabe:
long long expected = 4;
Eingabe:
long[] heights = new long[] {4};

Erwartete Ausgabe:
long expected = 4;

Erläuterung

A single bar of height 4 has area 4.

Referenzen

Diese Aufgabe wurde für CodeUtility angepasst. Beachte die oben genannten Vorgaben und Einschränkungen.

Von anderen lernen

Community-Lösungen

Noch keine veröffentlichten Lösungen. Löse die Aufgabe und teile als Erster eine Lösung.