Todos os desafios
Difícil 0 resolvidos 0% de aceitação

Trapping Rain Water

Compute how much rain water an elevation map holds.

Problema

Bars of width 1 have the given heights. After rain, water collects above each bar up to the lower of the tallest bars on its left and right. Compute the total trapped water. An O(n) two-pointer solution is expected.

Implement trapped_water(heights).

Input

heights: Bar heights from left to right.

Output

Return the total units of water.

Restrições

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

Exemplos

Exemplo 1
Entrada:
heights = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]

Saída esperada:
expected = 6
Entrada:
std::vector<long long> heights = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};

Saída esperada:
long long expected = 6;
Entrada:
long[] heights = new long[] {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};

Saída esperada:
long expected = 6;

Explicação

Water fills the dips: 1 + 1 + 2 + 1 + 1 = 6 units.

Exemplo 2
Entrada:
heights = [3, 2, 1]

Saída esperada:
expected = 0
Entrada:
std::vector<long long> heights = {3, 2, 1};

Saída esperada:
long long expected = 0;
Entrada:
long[] heights = new long[] {3, 2, 1};

Saída esperada:
long expected = 0;

Explicação

Heights only go down, so water runs off: 0.

Referências

Este desafio foi adaptado para o CodeUtility. Siga o enunciado e as restrições acima.

Aprenda com outros

Soluções da comunidade

Ainda não há soluções publicadas. Resolva este desafio para compartilhar a primeira.