VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-water-that-can-be-stored-between-two-buildings/

⇱ Maximum Area between Two Bars - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum Area between Two Bars

Last Updated : 7 Jun, 2026

Given an integer array height[], where height[i] represents the height of the ith bar arranged in a row, find the maximum rectangular area that can be formed by selecting any two bars. The area is calculated based on the original positions of the selected bars.

Examples:

Input: height[] = [2, 5, 4, 3, 7]
Output: 10
Explanation:

👁 blobid0_1780468637

The maximum rectangular area is formed by selecting the bars of heights 5 and 7. There are 2 bars between them, so the area is: min(5, 7) × 2 = 10.

Input: height[] = [1, 3, 4]
Output: 1
Explanation: Selecting bars 1 and 4 gives one bar between them, so the area is: min(1, 4) × 1 = 1.

[Naive Approach] Check All Pairs - O(n^2) Time O(1) Space

The idea is to consider every possible pair of bars and calculate the rectangular area formed by them. For each pair (i, j), the rectangle height is min(height[i], height[j]) and the width is the number of bars between them, i.e., (j - i - 1). Keep track of the maximum area obtained among all pairs.


Output
10

Time Complexity: O(n^2)
Auxiliary Space: O(1)

[Better Approach] Using Sorting - O(n log n) Time O(n) Space

The idea is to sort the bars according to their heights while keeping their original indices. For each bar, assume it is the shorter bar of the selected pair. Then, any bar processed after it in the sorted order will have height greater than or equal to the current bar, so the area will be limited by the current height. To maximize the area, we need the farthest such bar. This can be found by maintaining the minimum and maximum indices among the already processed taller bars and computing the best area using them.


Output
10

Time Complexity: O(n log n)
Auxiliary Space: O(n)

[Expected Approach] Using Two Pointers - O(n) Time O(1) Space

The idea is to use two pointers, one at the beginning and the other at the end of the array. For every pair of selected bars, the rectangle height is determined by the shorter bar, while the width is the number of bars between them. Since moving the taller bar inward only decreases the width without increasing the rectangle height, it cannot lead to a better answer. Therefore, move the pointer corresponding to the shorter bar inward and update the maximum area obtained. Repeat this process until the two pointers meet.

Let us understand working of approach:


Output
10

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

Comment