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.
[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.