Trapping Rain Water Problem – Tutorial with Illustrations
Last Updated :
15 Nov, 2024
Trapping Rainwater Problem states that given an array of n non-negative integers arr[] representing an elevation map where the width of each bar is 1, compute how much water it can trap after rain.

Trapping Rainwater Problem
Examples:
Let us understand Trapping Rainwater problem with the help of some examples:
Input: arr[] = {3, 0, 1, 0, 4, 0, 2}
Output: 10
Explanation: The expected rainwater to be trapped is shown in the above image.
Input: arr[] = {3, 0, 2, 0, 4}
Output: 7
Explanation: We trap 0 + 3 + 1 + 3 + 0 = 7 units.
Input: arr[] = {1, 2, 3, 4}
Output: 0
Explanation : We cannot trap water as there is no height bound on both sides
Input: arr[] = {2, 1, 5, 3, 1, 0, 4}
Output: 9
Explanation : We trap 0 + 1 + 0 + 1 + 3 + 4 + 0 = 9 units of water.
Observations:
The basic intuition of the problem is as follows:
- An element of the array can store water if there are higher bars on the left and the right.
- The amount of water to be stored in every position can be found by finding the heights of the higher bars on the left and right sides.
- The total amount of water stored is the summation of the water stored in each index.
- No water can be filled if there is no boundary on both sides.
Brute Force – O(n2) Time and O(1) Space:
Traverse every array element and find the highest bars on the left and right sides. Take the smaller of two heights. The difference between the smaller height and the height of the current element is the amount of water that can be stored in this array element.
C++
#include <bits/stdc++.h>
using namespace std;
// Function to return the maximum water that can be stored
int maxWater(vector<int>& arr)
{
int res = 0;
// For every element of the array
for (int i = 1; i < arr.size() - 1; i++) {
// Find the maximum element on its left
int left = arr[i];
for (int j = 0; j < i; j++)
left = max(left, arr[j]);
// Find the maximum element on its right
int right = arr[i];
for (int j = i + 1; j < arr.size(); j++)
right = max(right, arr[j]);
// Update the maximum water
res += (min(left, right) - arr[i]);
}
return res;
}
// Driver code
int main()
{
vector<int> arr = { 2, 1, 5, 3, 1, 0, 4 };
cout << maxWater(arr);
return 0;
}
C
#include <stdio.h>
// Function to return the maximum water that can be stored
int maxWater(int arr[], int n) {
int res = 0;
// For every element of the array
for (int i = 1; i < n - 1; i++) {
// Find the maximum element on its left
int left = arr[i];
for (int j = 0; j < i; j++)
if (arr[j] > left)
left = arr[j];
// Find the maximum element on its right
int right = arr[i];
for (int j = i + 1; j < n; j++)
if (arr[j] > right)
right = arr[j];
// Update the maximum water
res += (left < right ? left : right) - arr[i];
}
return res;
}
// Driver code
int main() {
int arr[] = { 2, 1, 5, 3, 1, 0, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d", maxWater(arr, n));
return 0;
}
Java
import java.util.*;
// Function to return the maximum water that can be stored
class GfG {
static int maxWater(int[] arr) {
int res = 0;
// For every element of the array
for (int i = 1; i < arr.length - 1; i++) {
// Find the maximum element on its left
int left = arr[i];
for (int j = 0; j < i; j++)
left = Math.max(left, arr[j]);
// Find the maximum element on its right
int right = arr[i];
for (int j = i + 1; j < arr.length; j++)
right = Math.max(right, arr[j]);
// Update the maximum water
res += Math.min(left, right) - arr[i];
}
return res;
}
// Driver code
public static void main(String[] args) {
int[] arr = { 2, 1, 5, 3, 1, 0, 4 };
System.out.println(maxWater(arr));
}
}
Python
# Function to return the maximum water that can be stored
def maxWater(arr):
res = 0
# For every element of the array
for i in range(1, len(arr) - 1):
# Find the maximum element on its left
left = arr[i]
for j in range(i):
left = max(left, arr[j])
# Find the maximum element on its right
right = arr[i]
for j in range(i + 1, len(arr)):
right = max(right, arr[j])
# Update the maximum water
res += (min(left, right) - arr[i])
return res
# Driver code
if __name__ == "__main__":
arr = [2, 1, 5, 3, 1, 0, 4]
print(maxWater(arr))
C#
using System;
class GfG {
// Function to return the maximum water that can be stored
static int maxWater(int[] arr) {
int res = 0;
// For every element of the array
for (int i = 1; i < arr.Length - 1; i++) {
// Find the maximum element on its left
int left = arr[i];
for (int j = 0; j < i; j++)
left = Math.Max(left, arr[j]);
// Find the maximum element on its right
int right = arr[i];
for (int j = i + 1; j < arr.Length; j++)
right = Math.Max(right, arr[j]);
// Update the maximum water
res += Math.Min(left, right) - arr[i];
}
return res;
}
// Driver code
static void Main() {
int[] arr = { 2, 1, 5, 3, 1, 0, 4 };
Console.WriteLine(maxWater(arr));
}
}
JavaScript
// Function to return the maximum water that can be stored
function maxWater(arr) {
let res = 0;
// For every element of the array
for (let i = 1; i < arr.length - 1; i++) {
// Find the maximum element on its left
let left = arr[i];
for (let j = 0; j < i; j++)
left = Math.max(left, arr[j]);
// Find the maximum element on its right
let right = arr[i];
for (let j = i + 1; j < arr.length; j++)
right = Math.max(right, arr[j]);
// Update the maximum water
res += Math.min(left, right) - arr[i];
}
return res;
}
// Driver code
let arr = [2, 1, 5, 3, 1, 0, 4];
console.log(maxWater(arr));
Computing prefix and suffix max for every index – O(n) Time and O(n) Space
In the previous approach, for every element we needed to calculate the highest element on the left and on the right.
So, to reduce the time complexity:
- For every element we first calculate and store the highest bar on the left and on the right (say stored in arrays left[] and right[]).
- Then iterate the array and use the calculated values to find the amount of water stored in this index,
which is the same as ( min(left[i], right[i]) – arr[i] )
C++
// C++ program to find maximum amount of water
// that can be trapped within given set of bars.
#include <bits/stdc++.h>
using namespace std;
int findWater(vector<int>& arr)
{
int n = arr.size();
// Left[i] contains height of tallest bar to the
// left of i'th bar including itself
vector<int> left(n);
// Right[i] contains height of tallest bar to
// the right of i'th bar including itself
vector<int> right(n);
// Initialize result
int res = 0;
// Fill left array
left[0] = arr[0];
for (int i = 1; i < n; i++)
left[i] = max(left[i - 1], arr[i]);
// Fill right array
right[n - 1] = arr[n - 1];
for (int i = n - 2; i >= 0; i--)
right[i] = max(right[i + 1], arr[i]);
// Calculate the accumulated water element by element
for (int i = 1; i < n - 1; i++) {
int minOf2 = min(left[i - 1], right[i + 1]);
if (minOf2 > arr[i]) {
res += minOf2 - arr[i];
}
}
return res;
}
// Driver program
int main()
{
vector<int> arr = { 2, 1, 5, 3, 1, 0, 4 };
cout << findWater(arr);
return 0;
}
C
#include <stdio.h>
// Function to find the maximum amount of water that can be trapped
int findWater(int arr[], int n) {
// Left[i] contains height of tallest bar to the
// left of i'th bar including itself
int left[n];
// Right[i] contains height of tallest bar to
// the right of i'th bar including itself
int right[n];
// Initialize result
int res = 0;
// Fill left array
left[0] = arr[0];
for (int i = 1; i < n; i++)
left[i] = left[i - 1] > arr[i] ? left[i - 1] : arr[i];
// Fill right array
right[n - 1] = arr[n - 1];
for (int i = n - 2; i >= 0; i--)
right[i] = right[i + 1] > arr[i] ? right[i + 1] : arr[i];
// Calculate the accumulated water element by element
for (int i = 1; i < n - 1; i++) {
int minOf2 = left[i - 1] < right[i + 1] ? left[i - 1] : right[i + 1];
if (minOf2 > arr[i]) {
res += minOf2 - arr[i];
}
}
return res;
}
// Driver program
int main() {
int arr[] = { 2, 1, 5, 3, 1, 0, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d", findWater(arr, n));
return 0;
}
Java
import java.util.*;
// Function to find the maximum amount of water that can be trapped
class GfG {
static int findWater(int[] arr) {
int n = arr.length;
// Left[i] contains height of tallest bar to the
// left of i'th bar including itself
int[] left = new int[n];
// Right[i] contains height of tallest bar to
// the right of i'th bar including itself
int[] right = new int[n];
// Initialize result
int res = 0;
// Fill left array
left[0] = arr[0];
for (int i = 1; i < n; i++)
left[i] = Math.max(left[i - 1], arr[i]);
// Fill right array
right[n - 1] = arr[n - 1];
for (int i = n - 2; i >= 0; i--)
right[i] = Math.max(right[i + 1], arr[i]);
// Calculate the accumulated water element by element
for (int i = 1; i < n - 1; i++) {
int minOf2 = Math.min(left[i - 1], right[i + 1]);
if (minOf2 > arr[i]) {
res += minOf2 - arr[i];
}
}
return res;
}
// Driver program
public static void main(String[] args) {
int[] arr = { 2, 1, 5, 3, 1, 0, 4 };
System.out.println(findWater(arr));
}
}
Python
# Function to find the maximum amount of water that can be trapped
def findWater(arr):
n = len(arr)
# Left[i] contains height of tallest bar to the
# left of i'th bar including itself
left = [0] * n
# Right[i] contains height of tallest bar to
# the right of i'th bar including itself
right = [0] * n
# Initialize result
res = 0
# Fill left array
left[0] = arr[0]
for i in range(1, n):
left[i] = max(left[i - 1], arr[i])
# Fill right array
right[n - 1] = arr[n - 1]
for i in range(n - 2, -1, -1):
right[i] = max(right[i + 1], arr[i])
# Calculate the accumulated water element by element
for i in range(1, n - 1):
minOf2 = min(left[i - 1], right[i + 1])
if minOf2 > arr[i]:
res += minOf2 - arr[i]
return res
# Driver program
arr = [2, 1, 5, 3, 1, 0, 4]
print(findWater(arr))
C#
using System;
class GfG {
// Function to find the maximum amount of water that can be trapped
static int findWater(int[] arr) {
int n = arr.Length;
// Left[i] contains height of tallest bar to the
// left of i'th bar including itself
int[] left = new int[n];
// Right[i] contains height of tallest bar to
// the right of i'th bar including itself
int[] right = new int[n];
// Initialize result
int res = 0;
// Fill left array
left[0] = arr[0];
for (int i = 1; i < n; i++)
left[i] = Math.Max(left[i - 1], arr[i]);
// Fill right array
right[n - 1] = arr[n - 1];
for (int i = n - 2; i >= 0; i--)
right[i] = Math.Max(right[i + 1], arr[i]);
// Calculate the accumulated water element by element
for (int i = 1; i < n - 1; i++) {
int minOf2 = Math.Min(left[i - 1], right[i + 1]);
if (minOf2 > arr[i]) {
res += minOf2 - arr[i];
}
}
return res;
}
// Driver program
static void Main() {
int[] arr = { 2, 1, 5, 3, 1, 0, 4 };
Console.WriteLine(findWater(arr));
}
}
JavaScript
// Function to find the maximum amount of water that can be trapped
function findWater(arr) {
let n = arr.length;
// Left[i] contains height of tallest bar to the
// left of i'th bar including itself
let left = new Array(n);
// Right[i] contains height of tallest bar to
// the right of i'th bar including itself
let right = new Array(n);
// Initialize result
let res = 0;
// Fill left array
left[0] = arr[0];
for (let i = 1; i < n; i++)
left[i] = Math.max(left[i - 1], arr[i]);
// Fill right array
right[n - 1] = arr[n - 1];
for (let i = n - 2; i >= 0; i--)
right[i] = Math.max(right[i + 1], arr[i]);
// Calculate the accumulated water element by element
for (let i = 1; i < n - 1; i++) {
let minOf2 = Math.min(left[i - 1], right[i + 1]);
if (minOf2 > arr[i]) {
res += minOf2 - arr[i];
}
}
return res;
}
// Driver program
let arr = [2, 1, 5, 3, 1, 0, 4];
console.log(findWater(arr));
Illustration :
Consider arr[] = {3, 0, 2, 0, 4}
Therefore, left[] = {3, 3, 3, 3, 4} and right[] = {4, 4, 4, 4, 4}
Now consider iterating using i from 0 to end and compute water stored at every index as min(left[i], right[i]) – arr[i]) and if it is greater than 0, then add it to the result.
Initialize : res = 0
For i = 0: res = 0 + 0 = 0
For i = 1: res = 0 + 3 = 3
For i = 2: res = 3 + 1 = 4
For i = 3: res = 4 + 3 = 7
For i = 4: res = 7 + 0 = 7
So total rain water trapped = 7
Best Approach – Using Two Pointers – O(n) Time and O(1) Space:
The approach is mainly based on the following facts:
- If we consider a subarray arr[left…right], we can decide the amount of water either for arr[left] or arr[right] if we know the left max (max element in arr[0…left-1]) and right max (max element in arr[right+1…n-1].
- If left max is less than the right max, then we can decide for arr[left]. Else we can decide for arr[right]
- If we decide for arr[left], then the amount of water would be left max – arr[left]
How does this work? Let us consider the case when left max is less than the right max. For arr[left], we know left max for it and we also know that the right max for it would not be less than left max because we already have a greater value in arr[right…n-1].
C++
#include <iostream>
#include <vector>
using namespace std;
int maxWater(vector<int> &arr) {
int left = 1;
int right = arr.size() - 2;
// lMax : Maximum in subarray arr[0..left-1]
// rMax : Maximum in subarray arr[right+1..n-1]
int lMax = arr[left - 1];
int rMax = arr[right + 1];
int res = 0;
while (left <= right) {
// If rMax is smaller, then we can decide the amount of water for arr[right]
if (rMax <= lMax) {
// Add the water for arr[right]
res += max(0, rMax - arr[right]);
// Update right max
rMax = max(rMax, arr[right]);
// Update right pointer as we have decided the amount of water for this
right -= 1;
} else {
// Add the water for arr[left]
res += max(0, lMax - arr[left]);
// Update left max
lMax = max(lMax, arr[left]);
// Update left pointer as we have decided water for this
left += 1;
}
}
return res;
}
// Driver code
int main() {
vector<int> arr = {2, 1, 5, 3, 1, 0, 4};
cout << maxWater(arr) << endl;
return 0;
}
C
#include <stdio.h>
// Function to find the maximum amount of water that can be trapped
int maxWater(int arr[], int n) {
int left = 1;
int right = n - 2;
// lMax : Maximum in subarray arr[0..left-1]
// rMax : Maximum in subarray arr[right+1..n-1]
int lMax = arr[left - 1];
int rMax = arr[right + 1];
int res = 0;
while (left <= right) {
// If rMax is smaller, then we can decide the amount of water for arr[right]
if (rMax <= lMax) {
// Add the water for arr[right]
res += (rMax - arr[right]) > 0 ? (rMax - arr[right]) : 0;
// Update right max
rMax = rMax > arr[right] ? rMax : arr[right];
// Update right pointer as we have decided the amount of water for this
right -= 1;
} else {
// Add the water for arr[left]
res += (lMax - arr[left]) > 0 ? (lMax - arr[left]) : 0;
// Update left max
lMax = lMax > arr[left] ? lMax : arr[left];
// Update left pointer as we have decided water for this
left += 1;
}
}
return res;
}
// Driver code
int main() {
int arr[] = {2, 1, 5, 3, 1, 0, 4};
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", maxWater(arr, n));
return 0;
}
Java
import java.util.*;
class GfG {
// Function to find the maximum amount of water that can be trapped
static int maxWater(int[] arr) {
int left = 1;
int right = arr.length - 2;
// lMax : Maximum in subarray arr[0..left-1]
// rMax : Maximum in subarray arr[right+1..n-1]
int lMax = arr[left - 1];
int rMax = arr[right + 1];
int res = 0;
while (left <= right) {
// If rMax is smaller, then we can decide the amount of water for arr[right]
if (rMax <= lMax) {
// Add the water for arr[right]
res += Math.max(0, rMax - arr[right]);
// Update right max
rMax = Math.max(rMax, arr[right]);
// Update right pointer as we have decided the amount of water for this
right -= 1;
} else {
// Add the water for arr[left]
res += Math.max(0, lMax - arr[left]);
// Update left max
lMax = Math.max(lMax, arr[left]);
// Update left pointer as we have decided water for this
left += 1;
}
}
return res;
}
// Driver code
public static void main(String[] args) {
int[] arr = {2, 1, 5, 3, 1, 0, 4};
System.out.println(maxWater(arr));
}
}
Python
# Function to find the maximum amount of water that can be trapped
def maxWater(arr):
left = 1
right = len(arr) - 2
# lMax : Maximum in subarray arr[0..left-1]
# rMax : Maximum in subarray arr[right+1..n-1]
lMax = arr[left - 1]
rMax = arr[right + 1]
res = 0
while left <= right:
# If rMax is smaller, then we can decide the amount of water for arr[right]
if rMax <= lMax:
# Add the water for arr[right]
res += max(0, rMax - arr[right])
# Update right max
rMax = max(rMax, arr[right])
# Update right pointer as we have decided the amount of water for this
right -= 1
else:
# Add the water for arr[left]
res += max(0, lMax - arr[left])
# Update left max
lMax = max(lMax, arr[left])
# Update left pointer as we have decided water for this
left += 1
return res
if __name__ == "__main__":
arr = [2, 1, 5, 3, 1, 0, 4]
print(maxWater(arr))
C#
using System;
class GfG {
// Function to find the maximum amount of water that can be trapped
static int maxWater(int[] arr) {
int left = 1;
int right = arr.Length - 2;
// lMax : Maximum in subarray arr[0..left-1]
// rMax : Maximum in subarray arr[right+1..n-1]
int lMax = arr[left - 1];
int rMax = arr[right + 1];
int res = 0;
while (left <= right) {
// If rMax is smaller, then we can decide the amount of water for arr[right]
if (rMax <= lMax) {
// Add the water for arr[right]
res += Math.Max(0, rMax - arr[right]);
// Update right max
rMax = Math.Max(rMax, arr[right]);
// Update right pointer as we have decided the amount of water for this
right -= 1;
} else {
// Add the water for arr[left]
res += Math.Max(0, lMax - arr[left]);
// Update left max
lMax = Math.Max(lMax, arr[left]);
// Update left pointer as we have decided water for this
left += 1;
}
}
return res;
}
// Driver code
static void Main() {
int[] arr = {2, 1, 5, 3, 1, 0, 4};
Console.WriteLine(maxWater(arr));
}
}
JavaScript
// Function to find the maximum amount of water that can be trapped
function maxWater(arr) {
let left = 1;
let right = arr.length - 2;
// lMax : Maximum in subarray arr[0..left-1]
// rMax : Maximum in subarray arr[right+1..n-1]
let lMax = arr[left - 1];
let rMax = arr[right + 1];
let res = 0;
while (left <= right) {
// If rMax is smaller, then we can decide the amount of water for arr[right]
if (rMax <= lMax) {
// Add the water for arr[right]
res += Math.max(0, rMax - arr[right]);
// Update right max
rMax = Math.max(rMax, arr[right]);
// Update right pointer as we have decided the amount of water for this
right -= 1;
} else {
// Add the water for arr[left]
res += Math.max(0, lMax - arr[left]);
// Update left max
lMax = Math.max(lMax, arr[left]);
// Update left pointer as we have decided water for this
left += 1;
}
}
return res;
}
// Driver code
let arr = [2, 1, 5, 3, 1, 0, 4];
console.log(maxWater(arr));
Using Stack – O(n) Time and O(n) Space:
We have already discussed a better approach than this, but this is really an interesting approach to learn. It is strongly recommended to refer next greater element, previous greater element and largest area in a histogram problems before moving forward. When we compute next greater element, we pop an item from the stack and mark current item as next greater of it. One important observation here is the item below every item in stack is the previous greater element. So for every element, we can compute both previous greater and next greater in one traversal and a stack. Now you must be wondering that for the trapping rain water problem, we need greatest on right and left (not closest greater). Please pause reading for a moment and thing how we can use next greater and previous greater for finding the amount of water.
- As discussed above, the idea is to find next greater and previous greater for every element using a stack and single traversal.
- When we have valid next greater and previous greater, we know for sure that we need to fill water between next greater and previous greater. We know a minimum amount also, so we fill the known amount. And when we consider previous greater and next greater we find their next and previous greater, and fill some more amount. We do this until we find next greatest and previous greatest.
- We do not fill the exact amount in a go and we also do not necessarily fill one by one, we fill all between next greater and previous greater.
C++
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
// Function to return the maximum water that can be stored
int maxWater(vector<int>& arr) {
stack<int> st;
int res = 0;
for (int i = 0; i < arr.size(); i++) {
// Pop all items smaller than arr[i]
while (!st.empty() && arr[st.top()] < arr[i]) {
int pop_height = arr[st.top()];
st.pop();
if (st.empty())
break;
// arr[i] is the next greater for the removed item
// and new stack top is the previous greater
int distance = i - st.top() - 1;
// Take the minimum of two heights (next and prev greater)
// and find the amount of water that we can fill in all
// bars between the two
int water = min(arr[st.top()], arr[i]) - pop_height;
res += distance * water;
}
st.push(i);
}
return res;
}
// Driver code
int main() {
vector<int> arr = {2, 1, 5, 3, 1, 0, 4};
cout << maxWater(arr);
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
// A structure to represent a stack
struct Stack {
int *array;
int top;
int capacity;
};
// Create a stack
struct Stack* createStack(int capacity) {
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
stack->capacity = capacity;
stack->top = -1;
stack->array = (int*)malloc(capacity * sizeof(int));
return stack;
}
// Stack is full when top is equal to the last index
int isFull(struct Stack* stack) {
return stack->top == stack->capacity - 1;
}
// Stack is empty when top is -1
int isEmpty(struct Stack* stack) {
return stack->top == -1;
}
// Function to add an item to stack
void push(struct Stack* stack, int item) {
if (isFull(stack))
return;
stack->array[++stack->top] = item;
}
// Function to remove an item from stack
int pop(struct Stack* stack) {
if (isEmpty(stack))
return -1;
return stack->array[stack->top--];
}
// Function to return the top from the stack without popping
int top(struct Stack* stack) {
return stack->array[stack->top];
}
// Function to return the maximum water that can be stored
int maxWater(int* arr, int n) {
struct Stack* st = createStack(n);
int res = 0;
for (int i = 0; i < n; i++) {
// Pop all items smaller than arr[i]
while (!isEmpty(st) && arr[top(st)] < arr[i]) {
int pop_height = arr[pop(st)];
if (isEmpty(st))
break;
// arr[i] is the next greater for the removed item
// and new stack top is the previous greater
int distance = i - top(st) - 1;
// Take the minimum of two heights (next and prev greater)
int water = (arr[top(st)] < arr[i]) ? arr[top(st)] : arr[i];
// Find the amount of water
water -= pop_height;
res += distance * water;
}
push(st, i);
}
free(st->array);
free(st);
return res;
}
// Driver code
int main() {
int arr[] = {2, 1, 5, 3, 1, 0, 4};
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d\n", maxWater(arr, n));
return 0;
}
Java
import java.util.Stack;
class GfG {
// Function to return the maximum water that can be stored
static int maxWater(int[] arr) {
Stack<Integer> st = new Stack<>();
int res = 0;
for (int i = 0; i < arr.length; i++) {
// Pop all items smaller than arr[i]
while (!st.isEmpty() && arr[st.peek()] < arr[i]) {
int pop_height = arr[st.pop()];
if (st.isEmpty())
break;
// arr[i] is the next greater for the removed item
// and new stack top is the previous greater
int distance = i - st.peek() - 1;
// Take the minimum of two heights (next and prev greater)
int water = Math.min(arr[st.peek()], arr[i]);
// Find the amount of water
water -= pop_height;
res += distance * water;
}
st.push(i);
}
return res;
}
// Driver code
public static void main(String[] args) {
int[] arr = {2, 1, 5, 3, 1, 0, 4};
System.out.println(maxWater(arr));
}
}
Python
# Function to return the maximum water that can be stored
def maxWater(arr):
st = []
res = 0
for i in range(len(arr)):
# Pop all items smaller than arr[i]
while st and arr[st[-1]] < arr[i]:
pop_height = arr[st.pop()]
if not st:
break
# arr[i] is the next greater for the removed item
# and new stack top is the previous greater
distance = i - st[-1] - 1
# Take the minimum of two heights (next and prev greater)
water = min(arr[st[-1]], arr[i])
# Find the amount of water
water -= pop_height
res += distance * water
st.append(i)
return res
# Driver code
arr = [2, 1, 5, 3, 1, 0, 4]
print(maxWater(arr))
C#
using System;
using System.Collections.Generic;
class GfG {
// Function to return the maximum water that can be stored
static int maxWater(int[] arr) {
Stack<int> st = new Stack<int>();
int res = 0;
for (int i = 0; i < arr.Length; i++) {
// Pop all items smaller than arr[i]
while (st.Count > 0 && arr[st.Peek()] < arr[i]) {
int pop_height = arr[st.Pop()];
if (st.Count == 0)
break;
// arr[i] is the next greater for the removed item
// and new stack top is the previous greater
int distance = i - st.Peek() - 1;
// Take the minimum of two heights (next and prev greater)
int water = Math.Min(arr[st.Peek()], arr[i]);
// Find the amount of water
water -= pop_height;
res += distance * water;
}
st.Push(i);
}
return res;
}
// Driver code
static void Main() {
int[] arr = {2, 1, 5, 3, 1, 0, 4};
Console.WriteLine(maxWater(arr));
}
}
JavaScript
// Function to return the maximum water that can be stored
function maxWater(arr) {
let st = [];
let res = 0;
for (let i = 0; i < arr.length; i++) {
// Pop all items smaller than arr[i]
while (st.length > 0 && arr[st[st.length - 1]] < arr[i]) {
let pop_height = arr[st.pop()];
if (st.length === 0)
break;
// arr[i] is the next greater for the removed item
// and new stack top is the previous greater
let distance = i - st[st.length - 1] - 1;
// Take the minimum of two heights (next and prev greater)
let water = Math.min(arr[st[st.length - 1]], arr[i]);
// Find the amount of water
water -= pop_height;
res += distance * water;
}
st.push(i);
}
return res;
}
// Driver code
let arr = [2, 1, 5, 3, 1, 0, 4];
console.log(maxWater(arr));
Similar Reads
Trapping Rain Water Problem - Tutorial with Illustrations
Trapping Rainwater Problem states that given an array of n non-negative integers arr[] representing an elevation map where the width of each bar is 1, compute how much water it can trap after rain. Examples:Let us understand Trapping Rainwater problem with the help of some examples: Input: arr[] = {
15+ min read
Trapping Rain Water in a Matrix
Given a matrix arr[][] of dimension M*N consisting of positive integers, where arr[i][j] represents the height of each unit cell, the task is to find the total volume of water trapped in the matrix after rain. Examples: Input: arr[][] = {{4, 2, 7}, {2, 1, 10}, {5, 10, 2}} Output: 1Explanation:The ra
14 min read
Water Jug Problem -Complete Tutorial
You are given a m liter jug and a n liter jug where 0 < m < n. Both the jugs are initially empty. The jugs don’t have markings to allow measuring smaller quantities. You have to use the jugs to measure d liters of water where d < n. Determine the minimum no of operations to be performed to
10 min read
Transportation Problem | Set 1 (Introduction)
Transportation problem is a special kind of Linear Programming Problem (LPP) in which goods are transported from a set of sources to a set of destinations subject to the supply and demand of the sources and destination respectively such that the total cost of transportation is minimized. It is also
2 min read
Count of operation required to water all the plants
Given an array arr[] of N integers where ith element represents the amount of water required by the plant at ith index and an integer K, the task is to calculate the count of operations required to water all the plants using a container that can hold at most K liters of water wherein each operation,
7 min read
Water Jug Problem using Memoization
Given two jugs with the maximum capacity of m and n liters respectively. The jugs don't have markings on them which can help us to measure smaller quantities. The task is to measure d liters of water using these two jugs. Hence our goal is to reach from initial state (m, n) to final state (0, d) or
9 min read
Maximizing Smallest Flower Height in Garden with Watering Constraint
You have a garden with n flowers lined up in a row. The height of ith flower is ai units. You will water them for k days. In one day you can water w continuous flowers (you can do this only once in a single day). Whenever you water a flower its height increases by 1 unit. You need to maximize the he
11 min read
Minimum distance to fetch water from well in a village
Given a 2-D matrix of characters of size n*m, where H - Represents a house, W - Represents a well, O - Represents an open ground, and N - Prohibited area(Not allowed to enter in this area). Every house in the village needs to take the water from the well, as the family members are so busy with their
13 min read
The Water Jug Problem - Count Min Steps
You are given a m liter jug and a n liter jug where 0 < m < n. Both the jugs are initially empty. The jugs don’t have markings to allow measuring smaller quantities. You have to use the jugs to measure d liters of water where d < n. Determine the minimum no of operations to be performed to
14 min read
Find the maximum angle at which we can tilt the bottle without spilling any water
Given a water bottle with the shape of a rectangular prism whose base is a square of side x cm and height y cm, the task is to find the maximum angle at which we can tilt the bottle without spilling any water, when z cubic cm of water is poured into the bottle, and gradually tilt the bottle around o
7 min read
Implementing Water Supply Problem using Breadth First Search
Given N cities that are connected using N-1 roads. Between Cities [i, i+1], there exists an edge for all i from 1 to N-1.The task is to set up a connection for water supply. Set the water supply in one city and water gets transported from it to other cities using road transport. Certain cities are b
10 min read
Transportation Problem | Set 3 (Least Cost Cell Method)
The North-West Corner method has been discussed in the previous article. In this article, the Least Cost Cell method will be discussed. Solution: According to the Least Cost Cell method, the least cost among all the cells in the table has to be found which is 1 (i.e. cell (O1, D2)). Now check the su
2 min read
Container with Most Water
Given n non-negative integers [Tex]a_1, a_2, ..., a_n[/Tex] where each represents a point at coordinate [Tex](i, a_i) [/Tex]. ' n ' vertical lines are drawn such that the two endpoints of line i is at [Tex](i, a_i) [/Tex]and [Tex](i, 0) [/Tex]. Find two lines, which together with x-axis forms a cont
9 min read
Transportation Problem | Set 7 ( Degeneracy in Transportation Problem )
Please go through this article first. This article will discuss degeneracy in transportation problem through an explained example. Solution: This problem is balanced transportation problem as total supply is equal to total demand. Initial basic feasible solution: Least Cost Cell Method will be used
3 min read
Water Jug problem using BFS
Given two empty jugs of m and n litres respectively. The jugs don't have markings to allow measuring smaller quantities. You have to use the jugs to measure d litres of water. The task is to find the minimum number of operations to be performed to obtain d litres of water in one of the jugs. In case
12 min read
Minimizing water collection distance in Geek's village
Geek's village is represented by a 2-D matrix of characters of size n*m, where H - Represents a houseW - Represents a well. - Represents an open groundN - Prohibited area(Not allowed to enter this area) Every house in the village needs to take the water from the well, as the family members are so bu
13 min read
Find amount of water wasted after filling the tank
Given the volume V of a tank in liter. There is a pump which is filling the tank at speed of M liter per minute. There is a leakage at the bottom of the tank which wasting water at speed N liter per minute. Given N is less than M. The task is to calculate how much amount of water will be wasted if l
5 min read
Water Connection Problem
Every house in the colony has at most one pipe going into it and at most one pipe going out of it. Tanks and taps are to be installed in a manner such that every house with one outgoing pipe but no incoming pipe gets a tank installed on its roof and every house with only an incoming pipe and no outg
11 min read
Shortest path in grid with obstacles
Given a grid of n rows and m columns. Currently, you are at point (0, 0) and must reach point (n-1, m-1). If any cell contains 0, it is a free cell, if it contains 1, there is an obstacle and you can't pass through the cell, and if it contains 2, that means it is free and if you step into this cell,
15 min read