Loading
Leetcode / 11. Container With Most Water

Pick a programming language:

Here is the source code for the solution to this problem.

class Solution {
    public int maxArea(int[] height) {
        int area = 0;
        int i = 0;
        int j = height.length - 1;

        while (i < j) {
            int rectangleWidth = j - i;
            // We have to take the smaller height otherwise water would overflow
            int rectangleHeight = Math.min(height[j], height[i]);
            // Compute the area and replace the maximum so far if that is the case
            area = Math.max(area, rectangleWidth * rectangleHeight);

            // Switch the smallest of the heights to try another column that might be possibly taller
            if (height[j] > height[i]) {
                i++;
            }
            else {
                j--;
            }
        }

        return area;
    }
}
Did you like the lesson? 😆👍
Consider a donation to support our work: