問題
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.
制約
0 ≤ length ≤ 200,000; 0 ≤ height ≤ 100,000
例
入力:
heights = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
期待される出力:
expected = 6
入力:
std::vector<long long> heights = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
期待される出力:
long long expected = 6;
入力:
long[] heights = new long[] {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
期待される出力:
long expected = 6;
解説
Water fills the dips: 1 + 1 + 2 + 1 + 1 = 6 units.
入力:
heights = [3, 2, 1]
期待される出力:
expected = 0
入力:
std::vector<long long> heights = {3, 2, 1};
期待される出力:
long long expected = 0;
入力:
long[] heights = new long[] {3, 2, 1};
期待される出力:
long expected = 0;
解説
Heights only go down, so water runs off: 0.
解き方のヒント
まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。
ヒント 1
各位置の水位は、左右それぞれで見た最も高い壁のうち低い方に制限されます。
ヒント 2
両端から境界を追い、現在の境界が低い側を優先して進めます。
ヒント 3
空入力と同じ高さが続く区間に注意します。その場で水量を決められるのは、低い側だけです。
目安の計算量
時間 O(n)、追加メモリ O(1)
参考資料
この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。