Khó 2 người đã giải Tỷ lệ chấp nhận 33.3%

Trapping Rain Water

Compute how much rain water an elevation map holds.

Bạn sẽ học được gì

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

Đề bài

Xem bản dịch

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.

Ràng buộc

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

Ví dụ

Ví dụ 1
Đầu vào:
heights = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]

Kết quả mong đợi:
expected = 6
Đầu vào:
std::vector<long long> heights = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};

Kết quả mong đợi:
long long expected = 6;
Đầu vào:
long[] heights = new long[] {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};

Kết quả mong đợi:
long expected = 6;

Giải thích

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

Ví dụ 2
Đầu vào:
heights = [3, 2, 1]

Kết quả mong đợi:
expected = 0
Đầu vào:
std::vector<long long> heights = {3, 2, 1};

Kết quả mong đợi:
long long expected = 0;
Đầu vào:
long[] heights = new long[] {3, 2, 1};

Kết quả mong đợi:
long expected = 0;

Giải thích

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

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

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

Gợi ý 2

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

Gợi ý 3

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

Độ phức tạp mong đợi

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

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

# Người giải Ngôn ngữ Thời gian Bộ nhớ AI đánh giá Lời giải
1 Н"Никита "Programmer" Python 885 ms - 5/5 Xem code
2 KKosake82 Python 933 ms - 4/5 Xem code

Học hỏi từ người khác

Lời giải cộng đồng

Cảnh báo: Có 2 lời giải đầy đủ bên dưới Hãy thử tự giải trước. Bạn vẫn có thể xem code của người khác và nhận xét của AI. Đăng nhập và giải thử thách để tham gia thảo luận.