Skip to content

Instantly share code, notes, and snippets.

@junminstorage
Created April 22, 2020 15:04
Show Gist options
  • Save junminstorage/8e8066d4cea9fc7aabe207294b589325 to your computer and use it in GitHub Desktop.
Save junminstorage/8e8066d4cea9fc7aabe207294b589325 to your computer and use it in GitHub Desktop.
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining.
Examples:
Input: arr[] = {2, 0, 2}
Output: 2
Structure is like below
| |
|_|
We can trap 2 units of water in the middle gap.
Input: arr[] = {3, 0, 0, 2, 0, 4}
Output: 10
Structure is like below
|
| |
| | |
|__|_|
We can trap "3*2 units" of water between 3 an 2,
"1 unit" on top of bar 2 and "3 units" between 2
and 4. See below diagram also.
Variation: if elevation of 0 means there is wall between it and no water can be trapped between those walls. What will be the changes to your solution?
@junminstorage
Copy link
Author

junminstorage commented Apr 22, 2020

Variation sample: => only 2 units of water now since there is gap of 0 in the middle

   #     # 
   #-# #-#     
   ### ###

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment