DDSA Solutions

Maximum Area Between Bars

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

Problem Overview

Given bar heights, find the largest rectangular area strictly between two bars (not including the bars themselves).

Advertisement

Intuition

Given bar heights, find the largest rectangular area strictly between two bars (not including the bars themselves). With pointers i and j, the width is j − i − 1 and height is limited by the shorter bar — same two-pointer idea as container with water, but width excludes both endpoints. Move the pointer at the shorter bar inward.

Algorithm

  1. 1Set i = 0, j = n − 1, area = 0.
  2. 2While i < j: update area with min(height[i], height[j]) * (j − i − 1).
  3. 3If height[i] <= height[j], increment i; else decrement j.
  4. 4Return area.

Example Walkthrough

Input: height = [2, 5, 1, 3, 4]

  1. 1. i=0, j=4: min(2,4)*3 = 6.
  2. 2. Move i (shorter left): i=1, j=4: min(5,4)*2 = 8.
  3. 3. Move j: continue until i >= j.
  4. 4. Maximum area between bars = 8.

Output: 8

Common Pitfalls

  • Width is (j − i − 1), not (j − i) — bars at i and j are excluded.
  • Move the shorter side; keeping the short bar fixes the height cap.
  • Empty or single-bar lists need no special two-pointer loop.
Maximum Area Between Bars.java
Java
// Approach: Two pointers at both ends. Area between bars i and j is min(height[i], height[j]) * (j - i - 1).
// Move the pointer at the shorter bar inward — a taller inner bar cannot beat the current bound.
// Time: O(n) Space: O(1)
import java.util.*;

class Solution {

    public int maxArea(List<Integer> height) {
        int n = height.size();
        int i = 0, j = n - 1;

        int area = 0;
        while (i < j) {

            area = Math.max(
                    area, Math.min(height.get(i), height.get(j)) * (j - i - 1)
            );

            if (height.get(i) <= height.get(j)) {
                i++;
            } else {
                j--;
            }
        }
        return area;
    }
}
Advertisement
Was this solution helpful?