Tutte le sfide
Difficile 1 risolta 100.0% di accettazione

Largest Rectangle in a Histogram

Find the largest rectangle that fits under a histogram.

Cosa imparerai

  • Find each bar's widest rectangle
  • Use a stack of increasing heights
  • Solve the problem in linear time

Problema

Mostra traduzione

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

The best rectangle for a bar depends on how far it can extend before a shorter bar blocks it.

Suggerimento 2

Use a monotonic increasing stack to find each bar’s nearest smaller bar on both sides.

Suggerimento 3

Don’t forget bars that never get popped until the end, and handle equal heights consistently.

Complessità attesa

O(n) time, O(n) extra space

Riferimenti

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

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

# Programmatore Linguaggio Tempo Memoria Voto dell'IA Soluzione
1 Н"Никита "Programmer" Python 996 ms - 5/5 Vedi il codice

Impara dagli altri

Soluzioni della community

Attenzione spoiler: 1 soluzione completa sotto Prova prima a risolverla da solo. Puoi comunque sbirciare il codice degli altri sviluppatori e le revisioni dell'IA. Accedi e risolvi la sfida per partecipare alla discussione.