Open In App
Related Articles

Maximum water that can be stored between two buildings

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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.

Examples: 

Input: arr[] = {1, 3, 4} 
Output:
Explanation: We have to calculate the maximum water that can be stored between any 2 buildings. 
Water between the buildings of height 1 and height 3 = 0. 
Water between the buildings of height 1 and height 4 = 1. 
Water between the buildings of height 3 and height 4 = 0. 
Hence maximum of all the cases is 1.

Input: arr[] = {2, 1, 3, 4, 6, 5} 
Output:
We remove the middle 4 buildings and get the total water stored as 2 * 4 = 8  

Recommended Practice

Naive approach: 

Check for all possible pairs and the pair which can hold maximum water will be the answer. Water stored between two buildings of heights h1 and h2 would be equal to minimum(h1, h2)*(distance between the buildings – 1), maximize this value to get the answer.

Below is the implementation of the above approach: 

C++

// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Return the maximum water that can be stored
int maxWater(int height[], int n)
{
    int maximum = 0;
 
    // Check all possible pairs of buildings
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            int current
                = (min(height[i], height[j]) * (j - i - 1));
 
            // Maximum so far
            maximum = max(maximum, current);
        }
    }
    return maximum;
}
 
// Driver code
int main()
{
    int height[] = { 2, 1, 3, 4, 6, 5 };
    int n = sizeof(height) / sizeof(height[0]);
    cout << maxWater(height, n);
    return 0;
}

                    

Java

// Java implementation of the above approach
class GFG {
 
    // Return the maximum water that can be stored
    static int maxWater(int height[], int n)
    {
        int max = 0;
 
        // Check all possible pairs of buildings
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                int current
                    = (Math.min(height[i], height[j])
                       * (j - i - 1));
 
                // Maximum so far
                max = Math.max(max, current);
            }
        }
        return max;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int height[] = { 2, 1, 3, 4, 6, 5 };
        int n = height.length;
        System.out.print(maxWater(height, n));
    }
}

                    

Python3

# Python3 implementation of the above approach
 
# Return the maximum water
# that can be stored
 
 
def maxWater(height, n):
    maximum = 0
 
    # Check all possible pairs of buildings
    for i in range(n - 1):
        for j in range(i + 1, n):
            current = min(height[i],
                          height[j]) * (j - i - 1)
 
            # Maximum so far
            maximum = max(maximum, current)
 
    return maximum
 
 
# Driver code
if __name__ == "__main__":
    height = [2, 1, 3, 4, 6, 5]
 
    n = len(height)
    print(maxWater(height, n))

                    

C#

// C# implementation of the above approach
using System;
 
class GFG {
 
    // Return the maximum water that can be stored
    static int maxWater(int[] height, int n)
    {
        int max = 0;
 
        // Check all possible pairs of buildings
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                int current
                    = (Math.Min(height[i], height[j])
                       * (j - i - 1));
 
                // Maximum so far
                max = Math.Max(max, current);
            }
        }
        return max;
    }
 
    // Driver code
    static public void Main()
    {
        int[] height = { 2, 1, 3, 4, 6, 5 };
        int n = height.Length;
        Console.WriteLine(maxWater(height, n));
    }
}

                    

Javascript

<script>
 
// Javascript implementation of the above approach
 
// Return the maximum water that can be stored
function maxWater( height, n)
{
    let maximum = 0;
 
    // Check all possible pairs of buildings
    for (let i = 0; i < n - 1; i++) {
        for (let j = i + 1; j < n; j++) {
            let current = (Math.min(height[i],
                               height[j])
                           * (j - i - 1));
 
            // Maximum so far
            maximum = Math.max(maximum, current);
        }
    }
    return maximum;
}
 
     
    // Driver program
     
    let height = [ 2, 1, 3, 4, 6, 5 ];
    let n = height.length;
    document.write(maxWater(height, n));
     
     
</script>

                    

Output
8

Time Complexity: O(N*N)
Auxiliary Space: O(1)

Maximum water that can be stored between two buildings using sorting 

Efficient approach: 

Sort the array according to increasing height without affecting the original indices i.e. make pairs of (element, index). Then for every element, assume it is the building with the minimum height among the two buildings required then the height of the required water will be equal to the height of the chosen building and the width will be equal to the index difference between the chosen building and the building to be found.

In order to choose the other building which maximizes the water, the other building has to be as far as possible and must be greater in height as compared to the currently chosen building.

Now, the problem gets reduced to finding the minimum and maximum indices on the right for every building in the sorted array.

Follow the steps below to implement the idea:

  • Create an array of pairs pairs[] of size N with each pair of the type (i, arr[i]) and sort pairs[] in increasing order of second element of pair.
  • Initialize minIndSoFar = pairs[n – 1].first and maxIndSoFar = pairs[n – 1].first as this would be the index of largest buildings on either sides of i and a variable maxi that will store the value of maximum water that can be stored.
  • Run a for loop with counter i from N – 2 to
    • Calculate the water that can be filled between the building on index i and minIndSoFar as ith building will be of same of less height than the building on minIndSoFar, so left = (pairs[i].second * (pairs[i].first – minIndSoFar – 1)).
    • Calculate the water that can be filled between the building on index i and maxIndSoFar as ith building will be of same of less height than the building on maxIndSoFar, so right = (pairs[i].second *(maxIndSoFar – pairs[i].first – 1)).
    • Now maximize maxi with max of left, right and maxi, update maxIndSoFar with max of maxIndSoFar and i, and minIndSoFar with min of maxIndSoFar and i. 
  • Return maxi.

Below is the implementation of the above approach:  

C++

// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
 
bool compareTo(pair<int, int> p1, pair<int, int> p2)
{
    return p1.second < p2.second;
}
 
// Return the maximum water that
// can be stored
int maxWater(int height[], int n)
{
 
    // Make pairs with indices
    pair<int, int> pairs[n];
    for (int i = 0; i < n; i++)
        pairs[i] = make_pair(i, height[i]);
 
    // Sort array based on heights
    sort(pairs, pairs + n, compareTo);
 
    // To store the min and max index so far
    // from the right
    int minIndSoFar = pairs[n - 1].first;
    int maxIndSoFar = pairs[n - 1].first;
    int maxi = 0;
 
    for (int i = n - 2; i >= 0; i--) {
 
        // Current building paired with
        // the building greater in height
        // and on the extreme left
        int left = 0;
        if (minIndSoFar < pairs[i].first) {
            left = (pairs[i].second
                    * (pairs[i].first - minIndSoFar - 1));
        }
 
        // Current building paired with
        // the building greater in height
        // and on the extreme right
        int right = 0;
        if (maxIndSoFar > pairs[i].first) {
            right = (pairs[i].second
                     * (maxIndSoFar - pairs[i].first - 1));
        }
 
        // Maximum so far
        maxi = max(left, max(right, maxi));
 
        // Update the maximum and minimum so far
        minIndSoFar = min(minIndSoFar, pairs[i].first);
        maxIndSoFar = max(maxIndSoFar, pairs[i].first);
    }
    return maxi;
}
 
// Driver code
int main()
{
    int height[] = { 2, 1, 3, 4, 6, 5 };
    int n = sizeof(height) / sizeof(height[0]);
 
    cout << maxWater(height, n);
}

                    

Java

// Java implementation of the above approach
import java.util.Arrays;
 
// Class to store the pairs
class Pair implements Comparable<Pair> {
    int ind, val;
 
    Pair(int ind, int val)
    {
        this.ind = ind;
        this.val = val;
    }
 
    @Override public int compareTo(Pair o)
    {
        if (this.val > o.val)
            return 1;
        return -1;
    }
}
 
class GFG {
 
    // Return the maximum water that can be stored
    static int maxWater(int height[], int n)
    {
 
        // Make pairs with indices
        Pair pairs[] = new Pair[n];
        for (int i = 0; i < n; i++)
            pairs[i] = new Pair(i, height[i]);
 
        // Sort array based on heights
        Arrays.sort(pairs);
 
        // To store the min and max index so far
        // from the right
        int minIndSoFar = pairs[n - 1].ind;
        int maxIndSoFar = pairs[n - 1].ind;
        int max = 0;
        for (int i = n - 2; i >= 0; i--) {
 
            // Current building paired with the building
            // greater in height and on the extreme left
            int left = 0;
            if (minIndSoFar < pairs[i].ind) {
                left = (pairs[i].val
                        * (pairs[i].ind - minIndSoFar - 1));
            }
 
            // Current building paired with the building
            // greater in height and on the extreme right
            int right = 0;
            if (maxIndSoFar > pairs[i].ind) {
                right
                    = (pairs[i].val
                       * (maxIndSoFar - pairs[i].ind - 1));
            }
 
            // Maximum so far
            max = Math.max(left, Math.max(right, max));
 
            // Update the maximum and minimum so far
            minIndSoFar
                = Math.min(minIndSoFar, pairs[i].ind);
            maxIndSoFar
                = Math.max(maxIndSoFar, pairs[i].ind);
        }
 
        return max;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int height[] = { 2, 1, 3, 4, 6, 5 };
        int n = height.length;
 
        System.out.print(maxWater(height, n));
    }
}

                    

Python3

# Python3 implementation of the above approach
from functools import cmp_to_key
 
 
def compareTo(p1, p2):
 
    return p1[1] - p2[1]
 
# Return the maximum water that
# can be stored
 
 
def maxWater(height, n):
 
    # Make pairs with indices
    pairs = [0 for i in range(n)]
    for i in range(n):
        pairs[i] = [i, height[i]]
 
    # Sort array based on heights
    pairs.sort(key=cmp_to_key(compareTo))
 
    # To store the min and max index so far
    # from the right
    minIndSoFar = pairs[n - 1][0]
    maxIndSoFar = pairs[n - 1][0]
    maxi = 0
 
    for i in range(n-2, -1, -1):
 
        # Current building paired with
        # the building greater in height
        # and on the extreme left
        left = 0
        if (minIndSoFar < pairs[i][0]):
            left = (pairs[i][1] *
                    (pairs[i][0] -
                     minIndSoFar - 1))
 
        # Current building paired with
        # the building greater in height
        # and on the extreme right
        right = 0
        if (maxIndSoFar > pairs[i][0]):
            right = (pairs[i][1] *
                     (maxIndSoFar -
                         pairs[i][0] - 1))
 
        # Maximum so far
        maxi = max(left, max(right, maxi))
 
        # Update the maximum and minimum so far
        minIndSoFar = min(minIndSoFar,
                          pairs[i][0])
        maxIndSoFar = max(maxIndSoFar,
                          pairs[i][0])
    return maxi
 
 
# Driver code
height = [2, 1, 3, 4, 6, 5]
n = len(height)
 
print(maxWater(height, n))

                    

C#

// C# implementation of the approach
using System;
using System.Linq;
 
class Program
{
 
    // Method to compare two pairs based on the second element
    static int CompareTo(Tuple<int, int> p1, Tuple<int, int> p2)
    {
        return p1.Item2.CompareTo(p2.Item2);
    }
 
    // Return the maximum water that can be stored
    static int MaxWater(int[] height, int n)
    {
        // Make pairs with indices
        Tuple<int, int>[] pairs = new Tuple<int, int>[n];
        for (int i = 0; i < n; i++)
            pairs[i] = Tuple.Create(i, height[i]);
 
        // Sort array based on heights
        Array.Sort(pairs, CompareTo);
 
        // To store the min and max index so far from the right
        int minIndSoFar = pairs[n - 1].Item1;
        int maxIndSoFar = pairs[n - 1].Item1;
        int maxi = 0;
 
        for (int i = n - 2; i >= 0; i--)
        {
            // Current building paired with the building
           // greater in height and on the extreme left
            int left = 0;
            if (minIndSoFar < pairs[i].Item1)
            {
                left = (pairs[i].Item2 * (pairs[i].Item1 - minIndSoFar - 1));
            }
 
            // Current building paired with the building greater
          // in height and on the extreme right
            int right = 0;
            if (maxIndSoFar > pairs[i].Item1)
            {
                right = (pairs[i].Item2 * (maxIndSoFar - pairs[i].Item1 - 1));
            }
 
            // Maximum so far
            maxi = Math.Max(left, Math.Max(right, maxi));
 
            // Update the maximum and minimum so far
            minIndSoFar = Math.Min(minIndSoFar, pairs[i].Item1);
            maxIndSoFar = Math.Max(maxIndSoFar, pairs[i].Item1);
        }
        return maxi;
    }
  static void Main(string[] args)
    {
        int[] height = { 2, 1, 3, 4, 6, 5 };
        int n = height.Length;
 
        Console.WriteLine(MaxWater(height, n));
    }
}

                    

Javascript

<script>
 
// JavaScript implementation of the above approach
 
 
function compareTo(p1,p2)
{
    return p1[1] - p2[1];
}
 
// Return the maximum water that
// can be stored
function maxWater(height, n)
{
     
    // Make pairs with indices
    let pairs = new Array(n);
    for(let i = 0; i < n; i++)
        pairs[i] = [i, height[i]];
         
    // Sort array based on heights
    pairs.sort(compareTo);   
     
    // To store the min and max index so far
    // from the right
    let minIndSoFar = pairs[n - 1][0];
    let maxIndSoFar = pairs[n - 1][0];
    let maxi = 0;
     
    for(let i = n - 2; i >= 0; i--)
    {
         
        // Current building paired with
        // the building greater in height
        // and on the extreme left
        let left = 0;
        if (minIndSoFar < pairs[i][0])
        {
            left = (pairs[i][1] *
                (pairs[i][0] -
                        minIndSoFar - 1));
        }
 
        // Current building paired with
        // the building greater in height
        // and on the extreme right
        let right = 0;
        if (maxIndSoFar > pairs[i][0])
        {
            right = (pairs[i][1] *
                        (maxIndSoFar -
                    pairs[i][0] - 1));
        }
 
        // Maximum so far
        maxi = Math.max(left, Math.max(right, maxi));
 
        // Update the maximum and minimum so far
        minIndSoFar = Math.min(minIndSoFar,
                        pairs[i][0]);
        maxIndSoFar = Math.max(maxIndSoFar,
                        pairs[i][0]);
    }
    return maxi;
}
 
// Driver code
 
let height = [ 2, 1, 3, 4, 6, 5 ];
let n = height.length;
 
document.write(maxWater(height, n),"</br>");
 
 
</script>

                    

Output
8

Time Complexity : O(N*log(N))
Auxiliary Space: O(N)

Maximum water that can be stored between two buildings using Two pointer approach

Below is the idea to solve the problem

Take two pointers i and j pointing to the first and the last building respectively and calculate the water that can be stored between these two buildings. Now increment i if height[i] < height[j] else decrement j. This is because the water that can be trapped is dependent on the height of the small building and moving from the greater height building will just reduce the amount of water instead of maximizing it. In the end, print the maximum amount of water calculated so far.

Follow the below steps to implement the idea:

  • Initialize variable maximum to store maximum water that can be stored, i and j pointing to the first and the last.
  • Run a while loop till i < j
    • If height[i] < height[j] update maximum = max(maximum, (j – i – 1) * height[i]) and increment i by 1.
    • Else maximum will be updated according to right height i.e. building at j maximum = max(maximum, (j – i – 1) * height[j]) and decrement j by 1.
  • return maximum.

Below is the implementation of the above approach:  

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Return the maximum water that can be stored
int maxWater(int height[], int n)
{
 
    // To store the maximum water so far
    int maximum = 0;
 
    // Both the pointers are pointing at the first
    // and the last buildings respectively
    int i = 0, j = n - 1;
 
    // While the water can be stored between
    // the currently chosen buildings
    while (i < j) {
 
        // Update maximum water so far and increment i
        if (height[i] < height[j]) {
            maximum = max(maximum, (j - i - 1) * height[i]);
            i++;
        }
 
        // Update maximum water so far and decrement j
        else {
            maximum = max(maximum, (j - i - 1) * height[j]);
            j--;
        }
    }
 
    return maximum;
}
 
// Driver code
int main()
{
 
    int height[] = { 2, 1, 3, 4, 6, 5 };
 
    int n = sizeof(height) / sizeof(height[0]);
 
    cout << (maxWater(height, n));
}
 
// This code is contributed by CrazyPro

                    

Java

// Java implementation of the approach
import java.util.Arrays;
 
class GFG {
 
    // Return the maximum water that can be stored
    static int maxWater(int height[], int n)
    {
 
        // To store the maximum water so far
        int max = 0;
 
        // Both the pointers are pointing at the first
        // and the last buildings respectively
        int i = 0, j = n - 1;
 
        // While the water can be stored between
        // the currently chosen buildings
        while (i < j) {
 
            // Update maximum water so far and increment i
            if (height[i] < height[j]) {
                max = Math.max(max,
                               (j - i - 1) * height[i]);
                i++;
            }
 
            // Update maximum water so far and decrement j
            else if (height[j] < height[i]) {
                max = Math.max(max,
                               (j - i - 1) * height[j]);
                j--;
            }
 
            // Any of the pointers can be updated (or both)
            else {
                max = Math.max(max,
                               (j - i - 1) * height[i]);
                i++;
                j--;
            }
        }
 
        return max;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int height[] = { 2, 1, 3, 4, 6, 5 };
        int n = height.length;
 
        System.out.print(maxWater(height, n));
    }
}

                    

Python3

# Python3 implementation of the approach
 
# Return the maximum water that can be stored
 
 
def maxWater(height, n):
 
    # To store the maximum water so far
    maximum = 0
 
    # Both the pointers are pointing at the first
    # and the last buildings respectively
    i = 0
    j = n - 1
 
    # While the water can be stored between
    # the currently chosen buildings
    while (i < j):
 
        # Update maximum water so far and increment i
        if (height[i] < height[j]):
            maximum = max(maximum, (j - i - 1) * height[i])
            i += 1
 
        # Update maximum water so far and decrement j
        elif (height[j] < height[i]):
            maximum = max(maximum, (j - i - 1) * height[j])
            j -= 1
 
        # Any of the pointers can be updated (or both)
        else:
            maximum = max(maximum, (j - i - 1) * height[i])
            i += 1
            j -= 1
 
    return maximum
 
 
# Driver code
height = [2, 1, 3, 4, 6, 5]
 
n = len(height)
 
print(maxWater(height, n))
 
# This code is contributed by CrazyPro

                    

C#

// C# implementation of the approach
using System;
 
class GFG {
 
    // Return the maximum water that can be stored
    static int maxWater(int[] height, int n)
    {
 
        // To store the maximum water so far
        int max = 0;
 
        // Both the pointers are pointing at the first
        // and the last buildings respectively
        int i = 0, j = n - 1;
 
        // While the water can be stored between
        // the currently chosen buildings
        while (i < j) {
 
            // Update maximum water so far and increment i
            if (height[i] < height[j]) {
                max = Math.Max(max,
                               (j - i - 1) * height[i]);
                i++;
            }
 
            // Update maximum water so far and decrement j
            else if (height[j] < height[i]) {
                max = Math.Max(max,
                               (j - i - 1) * height[j]);
                j--;
            }
 
            // Any of the pointers can be updated (or both)
            else {
                max = Math.Max(max,
                               (j - i - 1) * height[i]);
                i++;
                j--;
            }
        }
 
        return max;
    }
 
    // Driver code
    static public void Main()
    {
 
        int[] height = { 2, 1, 3, 4, 6, 5 };
        int n = height.Length;
 
        Console.Write(maxWater(height, n));
    }
}
 
// This code is contributed by jit_t

                    

Javascript

<script>
 
// Javascript implementation of the approach
 
// Return the maximum water that can be stored
function maxWater(height, n)
{
 
    // To store the maximum water so far
    var maximum = 0;
 
    // Both the pointers are pointing at the first
    // and the last buildings respectively
    var i = 0, j = n - 1;
 
    // While the water can be stored between
    // the currently chosen buildings
    while (i < j)
    {
 
        // Update maximum water so far and increment i
        if (height[i] < height[j])
        {
            maximum = Math.max(maximum, (j - i - 1) * height[i]);
            i++;
        }
 
        // Update maximum water so far and decrement j
        else if (height[j] < height[i])
        {
            maximum = Math.max(maximum, (j - i - 1) * height[j]);
            j--;
        }
 
        // Any of the pointers can be updated (or both)
        else
        {
            maximum = Math.max(maximum, (j - i - 1) * height[i]);
            i++;
            j--;
        }
    }
 
    return maximum;
}
 
 
// Driver code
var height = [ 2, 1, 3, 4, 6, 5 ];
var n = height.length;
document.write(maxWater(height, n))
 
 
 
</script>

                    

Output
8

Time Complexity: O(N)
Auxiliary Space: O(1)



Last Updated : 15 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads