Algo-Sim › Two Pointers

Container With Most Water

Medium · Two Pointers · step through it in Java, Python and C++ on your own input

Pick two walls that, with the x-axis, hold the most water. Always move the shorter wall inward.

Problem

You are given n vertical walls, where wall i stands at x = i with height height[i]. Choose two walls; together with the x-axis they form a container that holds min(height[i], height[j]) · (j − i) units of water. Return the largest amount any pair can hold.

Constraints

Edge cases to test

Follow-up questions

Why is moving the shorter wall always safe?
Any container using the shorter wall and a wall further in is narrower and no taller, so the shorter wall can be discarded: O(n) total.
How does this differ from Trapping Rain Water?
Here you choose two walls and ignore the ones in between; there every bar traps water up to the lower of its tallest walls on each side.

Solution

Java

public int maxArea(int[] height) {
    int left = 0, right = height.length - 1;
    int best = 0;
    while (left < right) {
        int h = Math.min(height[left], height[right]);
        best = Math.max(best, h * (right - left));
        if (height[left] < height[right]) {
            left++;
        } else {
            right--;
        }
    }
    return best;
}

Python

def max_area(height):
    left, right = 0, len(height) - 1
    best = 0
    while left < right:
        h = min(height[left], height[right])
        best = max(best, h * (right - left))
        if height[left] < height[right]:
            left += 1
        else:
            right -= 1
    return best

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int maxArea(vector<int> &height) {
        int left = 0, right = int(height.size()) - 1;
        int best = 0;
        while (left < right) {
            int h = std::min(height[left], height[right]);
            best = std::max(best, h * (right - left));
            if (height[left] < height[right]) {
                left++;
            } else {
                right--;
            }
        }
        return best;
    }
};

More Two Pointers problems