ยาก 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Trapping Rain Water

Compute how much rain water an elevation map holds.

โจทย์

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.

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก