Le migliori 150 intervisteFacile

Intrappolare l'acqua piovana

Guida dettagliata e implementazione Python per il problema "Trapping Rain Water".

Dichiarazione del problema

Facile

Dati n numeri interi non negativi che rappresentano una mappa di elevazione in cui la larghezza di ciascuna barra è 1, calcola quanta acqua può intrappolare dopo la pioggia.

Scrivi una funzione trap(height: List[int]) -> int.

Vincoli
  • n == len(height)
  • 1 <= n <= 2 * 10^4
  • 0 <= height[i] <= 10^5

Esempi

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?
Prendi in considerazione l'utilizzo di strutture dati specifiche di Two Pointers come set o heap.
Edge Cases to Watch
  • Strutture di input vuote
  • Ingressi a elemento singolo
  • Grandi limiti numerici

Pronto a risolvere?

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

Apri nell'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

Risorse Python consigliate

Espandi le tue conoscenze con tutorial interattivi, foglietti illustrativi e confronti di codici correlati.