Schwierig 0 gelöst 0% Erfolgsquote

Trapping Rain Water

Compute how much rain water an elevation map holds.

Problem

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.

Einschränkungen

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

Beispiele

Beispiel 1
Eingabe:
heights = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]

Erwartete Ausgabe:
expected = 6
Eingabe:
std::vector<long long> heights = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};

Erwartete Ausgabe:
long long expected = 6;
Eingabe:
long[] heights = new long[] {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};

Erwartete Ausgabe:
long expected = 6;

Erläuterung

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

Beispiel 2
Eingabe:
heights = [3, 2, 1]

Erwartete Ausgabe:
expected = 0
Eingabe:
std::vector<long long> heights = {3, 2, 1};

Erwartete Ausgabe:
long long expected = 0;
Eingabe:
long[] heights = new long[] {3, 2, 1};

Erwartete Ausgabe:
long expected = 0;

Erläuterung

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

Referenzen

Diese Aufgabe wurde für CodeUtility angepasst. Beachte die oben genannten Vorgaben und Einschränkungen.

Von anderen lernen

Community-Lösungen

Noch keine veröffentlichten Lösungen. Löse die Aufgabe und teile als Erster eine Lösung.