The Wayback Machine - https://web.archive.org/web/20241001110639/https://www.geeksforgeeks.org/trapping-rain-water/
Open In App

Trapping Rain Water Problem – Tutorial with Illustrations

Last Updated : 25 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

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[] = {10, 9, 0, 5}
Output: 5
Explanation : We trap 0 + 0 + 5 + 0 = 5

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 = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 };
    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[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 };
    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 = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 };
        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 = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
    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 = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 };
        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 = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1];
console.log(maxWater(arr));

Output
6

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 = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 };
    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[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 };
    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 = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 };
        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 = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
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 = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 };
        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 = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1];
console.log(findWater(arr));

Output
6

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:

  1. 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].
  2. If left max is less than the right max, then we can decide for arr[left]. Else we can decide for arr[right]
  3. 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]. Any other value from left+1 to right – 1 would anyways be more than left max.

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 = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
    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[] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
    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 = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
        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

# Driver code
arr = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
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 = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
        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 = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1];
console.log(maxWater(arr));

Output
6

Illustration:

Consider arr[] = {3, 0, 5, 0, 4}
Initial values:

  • left = 1, right = 3, lMax = arr[0] = 3, rMax = arr[4] = 4
  • res = 0 (stores total water trapped)
  1. left = 1, right = 3:: Since lMax < rMax, we fill water in arr[left] as 3- 0 = 3,
  2. left = 2, right = 3: lMax < rMax, but arr[left] > lMax, we we do not fill water, we update lMax = 5
  3. left = 3, right = 3: Since lMax >= rMax, we fill water in arr[right] as 4-0

Total water trapped = 3 + 0 + 4 = 7

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.

  1. As discussed above, the idea is to find next greater and previous greater for every element using a stack and single traversal.
  2. 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.
  3. 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 = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
    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[] = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
    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 = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
        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 = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]
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 = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
        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 = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1];
console.log(maxWater(arr));

Output
6




Similar Reads

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 rain water can be trapped in the following way: The
14 min read
Program to check if water tank overflows when n solid balls are dipped in the water tank
Given the dimensions of cylindrical water tank, spherical solid balls and the amount of water present in the tank check if water tank will overflow when balls are dipped in the water tank. Examples : input : H = 10, r = 5 h = 5 N = 2, R = 2 output : Not in overflow state Explanation : water tank capacity = 3.14 * r * r * H = 3.14 * 5 * 5 * 10 = 785
8 min read
Probability of rain on N+1th day
Given an array of 1 and 0's, where Ai = 1 denotes that ith day was a rainy day and Ai = 0 denotes it was not a rainy day. The task is to find the probability that the N+1th was a rainy day. Examples: Input: a[] = {0, 0, 1, 0} Output: .25 Since one day was rainy out of 4 days, hence the probability on 5th day will be 0.25Input: a[] = {1, 0, 1, 0, 1,
4 min read
Water drop problem
Consider a pipe of length L. The pipe has N water droplets at N different positions within it. Each water droplet is moving towards the end of the pipe(x=L) at different rates. When a water droplet mixes with another water droplet, it assumes the speed of the water droplet it is mixing with. Determine the no of droplets that come out of the end of
10 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 (d, 0). Examples: Input: 4 3 2 Output: (0, 0) --
9 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 blocked which means that water cannot pass through
10 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 outgoing pipe gets a tap. Given two integers n and p d
11 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 obtain d liters of water in one of the two jugs. T
14 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 of no solution exist, return -1. The operations y
12 min read
Secretary Problem (A Optimal Stopping Problem)
The Secretary Problem also known as marriage problem, the sultan's dowry problem, and the best choice problem is an example of Optimal Stopping Problem. This problem can be stated in the following form: Imagine an administrator who wants to hire the best secretary out of n rankable applicants for a position. The applicants are interviewed one by on
12 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 here to find the initial basic feasible solution.
3 min read
Nuts & Bolts Problem (Lock & Key problem) using Quick Sort
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means a nut can only be compared with a bolt and a bolt can only be compared with a nut to see which
12 min read
Nuts & Bolts Problem (Lock & Key problem) using Hashmap
Given a set of n nuts of different sizes and n bolts of different sizes. There is a one-one mapping between nuts and bolts. Match nuts and bolts efficiently. Constraint: Comparison of a nut to another nut or a bolt to another bolt is not allowed. It means nut can only be compared with bolt and bolt can only be compared with a nut to see which one i
5 min read
Difference between 0/1 Knapsack problem and Fractional Knapsack problem
What is Knapsack Problem?Suppose you have been given a knapsack or bag with a limited weight capacity, and each item has some weight and value. The problem here is that "Which item is to be placed in the knapsack such that the weight limit does not exceed and the total value of the items is as large as possible?". Consider the real-life example. Su
13 min read
Speed of boat in still water from speed of stream and times taken
Write a program to determine speed of the boat in still water(B) given the speed of the stream(S in km/hr), the time taken (for same point) by the boat upstream(T1 in hr) and downstream(T2 in hr). Examples: Input : T1 = 4, T2 = 2, S = 5 Output : B = 15 Input : T1 = 6, T2 = 1, S = 7 Output : B = 9.8 Prerequisite : Speed of boat upstream and downstre
4 min read
Minimum number of Water to Land conversion to make two islands connected in a Grid
Given a 2D grid arr[][] of ‘W’ and ‘L’ where 'W' denotes water and ‘L’ denotes land, the task is to find the minimum number of water components ‘W’ that must be changed to land component ‘L’ so that two islands becomes connected. An island is the set of connected ‘L’s. Note: There can be only two disjoint islands. Examples: Input: arr[][] = {{'W',
10 min read
Maximize count of empty water bottles from N filled bottles
Given two integers N and E, where N represents the number of full water bottles and E represents the number of empty bottles that can be exchanged for a full water bottle. The task is to find the maximum number of water bottles that can be emptied. Examples: Input: N = 9, E = 3Output: 13Explanation:Initially, there are 9 fully filled water bottles.
6 min read
Water Game
Given an empty glass, this glass has to be filled with water and the task is to find the maximum amount of water that the glass has held at any moment. Given conditions: The program takes an input N denoting the number of steps. Each step consists of two inputs T and X where T is the flag condition denoting whether the X ml of water has to be poure
6 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 leakage is seen after filling the full tank.Example
5 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 one of the sides of the base. Examples: Input: x =
7 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, You can move to the adjacent plant to the left or
7 min read
Atlantic pacific water flow
There is an N x M rectangular island that borders both the Pacific Ocean and the Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges. The island is partitioned into a grid of square cells. The island receives a lot of rain, and the rainwater can flow to neighb
12 min read
Minimum number of Water to Land conversion to make two islands connected in a Grid | Set 2
Given a 2D grid arr[][] of ‘W’ and ‘L’ where ‘W’ denotes water and ‘L’ denotes land, the task is to find the minimum number of water components ‘W’ that must be changed to land component ‘L’ so that two islands becomes connected. An island is the set of connected 'L's Note: There can be only two disjoint islands. Examples: Input: arr[][] = {{‘W’, ‘
13 min read
Minimize water to fill all tanks connected by given circuit
Given N tanks connected like a tree, the connections between them in an array Edge[][], and the capacity of each tank in the array cap[], the task is to find the minimum amount of water required to pour into the given tank such that all the tanks are filled. Note: When a tank is filled, the remaining amount of water is equally distributed among the
9 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 busy with their work, so every family wants to take
13 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 work, so every family wants to take the water fro
13 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 container, such that the container contains the most w
11 min read
Maximum water that can be stored between two buildings
Given an integer array that represents the heights of N buildings. The task is to delete N - 2 buildings such that the water that can be trapped between the remaining two buildings is maximum. The total water trapped between two buildings is a gap between them (the number of buildings removed) multiplied by the height of the smaller building. Examp
15+ min read
Minimum sprinklers required to be turned on to water the plants
Given an array arr[] consisting of N integers, where the ith element represents the range of a sprinkler i.e [i-arr[i], i+arr[i]] it can water, the task is to find the minimum number of the sprinkler to be turned on to water every plant at the gallery. If it is not possible to water every plant, then print -1.Note: If arr[i] = -1, then the sprinkle
10 min read
Program to find amount of water in a given glass
There are some glasses with equal capacity as 1 litre. The glasses are kept as follows: 1 2 3 4 5 6 7 8 9 10 You can put water to the only top glass. If you put more than 1-litre water to 1st glass, water overflows and fills equally in both 2nd and 3rd glasses. Glass 5 will get water from both 2nd glass and 3rd glass and so on. If you have X litre
15+ min read