Todos los desafíos
Difícil 0 resueltos 0% de aceptación

Largest Rectangle in a Histogram

Find the largest rectangle that fits under a histogram.

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.

Restricciones

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

Ejemplos

Ejemplo 1
Entrada:
heights = [2, 1, 5, 6, 2, 3]

Salida esperada:
expected = 10
Entrada:
std::vector<long long> heights = {2, 1, 5, 6, 2, 3};

Salida esperada:
long long expected = 10;
Entrada:
long[] heights = new long[] {2, 1, 5, 6, 2, 3};

Salida esperada:
long expected = 10;

Explicación

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

Ejemplo 2
Entrada:
heights = [4]

Salida esperada:
expected = 4
Entrada:
std::vector<long long> heights = {4};

Salida esperada:
long long expected = 4;
Entrada:
long[] heights = new long[] {4};

Salida esperada:
long expected = 4;

Explicación

A single bar of height 4 has area 4.

Referencias

Este reto está adaptado para CodeUtility. Sigue el enunciado y las restricciones indicadas arriba.

Aprende de otros

Soluciones de la comunidad

Aún no hay soluciones publicadas. Resuelve este reto para compartir la primera.