難しい 2件解決済み 正答率33.3%

Trapping Rain Water

Compute how much rain water an elevation map holds.

このチャレンジで学べること

  • Compute water above each bar
  • Use left and right maximums
  • Solve it with two pointers in O(n)

問題

翻訳を表示

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

例

例 1
入力:
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.

例 2
入力:
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

Each position’s water level is limited by the shorter tallest bar seen on its left and right.

ヒント 2

Track boundaries from both ends, always advancing the side with the smaller current boundary.

ヒント 3

Be careful with empty input and equal-height plateaus; only the smaller side can determine trapped water there.

目安の計算量

O(n) time, O(1) extra space

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

# コーダー 言語 時間 メモリ AI 評価 解答
1 Н"Никита "Programmer" Python 885 ms - 5/5 コードを見る
2 KKosake82 Python 933 ms - 4/5 コードを見る

他の人の解答から学ぶ

コミュニティの解答

ネタバレ注意: この下に解答が2件あります まずは自分で挑戦してみましょう。他の開発者のコードやAIレビューも見ることができます。 サインインして課題を解くと議論に参加できます。