150 principais entrevistasFácil

Retendo a água da chuva

Guia detalhado e implementação de Python para o problema de 'Retenção de Água da Chuva'.

Declaração do problema

Fácil

Dados n inteiros não negativos representando um mapa de elevação onde a largura de cada barra é 1, calcule quanta água ela pode reter após chover.

Escreva uma função trap(height: List[int]) -> int.

Restrições
  • n == len(height)
  • 1 <= n <= 2 * 10^4
  • 0 <= height[i] <= 10^5

Exemplos

Example 1
Input
height = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
Output
6
Explanation

The elevation map traps 6 units of rain water. Water fills between the bars: 1 unit above index 2, 1 unit above index 4, 2 units above index 5, 1 unit above index 6, and 1 unit above index 9.

Example 2
Input
height = [4, 2, 0, 3, 2, 5]
Output
9
Explanation

Water trapped: 2 above index 1, 4 above index 2, 1 above index 3, 2 above index 4 = 9 total.

Need a Hint?
Considere o uso de estruturas de dados específicas de dois ponteiros, como conjuntos ou heaps.
Edge Cases to Watch
  • Estruturas de entrada vazias
  • Entradas de elemento único
  • Grandes limites numéricos

Pronto para resolver?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Abrir no Editor
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

Recursos Python recomendados

Expanda seu conhecimento com tutoriais interativos relacionados, folhas de dicas e comparações de código.