Torna alle sfide
Difficile 0 risolte 0% di accettazione

Largest Rectangle in a Histogram

Find the largest rectangle that fits under a histogram.

Cosa imparerai

  • Trovare il rettangolo più largo per ogni barra
  • Usare uno stack di altezze crescenti
  • Risolvere il problema in tempo lineare

Problema

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.

Vincoli

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

Esempi

Esempio 1
Input:
heights = [2, 1, 5, 6, 2, 3]

Output atteso:
expected = 10
Input:
std::vector<long long> heights = {2, 1, 5, 6, 2, 3};

Output atteso:
long long expected = 10;
Input:
long[] heights = new long[] {2, 1, 5, 6, 2, 3};

Output atteso:
long expected = 10;

Spiegazione

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

Esempio 2
Input:
heights = [4]

Output atteso:
expected = 4
Input:
std::vector<long long> heights = {4};

Output atteso:
long long expected = 4;
Input:
long[] heights = new long[] {4};

Output atteso:
long expected = 4;

Spiegazione

A single bar of height 4 has area 4.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

Il rettangolo migliore per una barra dipende da quanto può estendersi prima che una barra più bassa lo blocchi.

Suggerimento 2

Usa uno stack monotono crescente per trovare, per ogni barra, la barra più piccola più vicina su entrambi i lati.

Suggerimento 3

Non dimenticare le barre che restano nello stack fino alla fine, e gestisci in modo coerente le altezze uguali.

Complessità attesa

tempo O(n), spazio aggiuntivo O(n)

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.