DDSA Solutions

Container With Most Water

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

Intuition

Two pointers from both ends. Area = min(height[l], height[r]) * (r-l). Move the shorter side inward.

Algorithm

  1. 1l=0, r=n-1. max_area=0.
  2. 2While l<r: area = min(height[l],height[r])*(r-l). max_area = max. Move shorter side.

Common Pitfalls

  • Moving shorter side can only increase area. Moving taller side can only decrease width without gain.
Container With Most Water.java
Java
// Approach: Two pointers starting at both ends. Move the pointer with the shorter height inward.
// Track the maximum area computed at each step.
// Time: O(n) Space: O(1)
class Solution {

    public int maxWater(int arr[]) {
        int n = arr.length;
        int s = 0;
        int e = n - 1;
        int m = 0;

        while (s <= e) {
            int w = e - s;
            int h = Math.min(arr[s], arr[e]);
            m = Math.max(m, w * h);

            if (arr[s] < arr[e])
                s++;
            else
                e--;
        }
        
        return m;
    }
}
Advertisement
Was this solution helpful?