Loading

LeetCode problem#11

Container With Most Water

Solved in 1 languageJava

Solve it on LeetCode(opens in a new tab)

Solution

25 lines
1class Solution {
2    public int maxArea(int[] height) {
3        int area = 0;
4        int i = 0;
5        int j = height.length - 1;
6
7        while (i < j) {
8            int rectangleWidth = j - i;
9            // We have to take the smaller height otherwise water would overflow
10            int rectangleHeight = Math.min(height[j], height[i]);
11            // Compute the area and replace the maximum so far if that is the case
12            area = Math.max(area, rectangleWidth * rectangleHeight);
13
14            // Switch the smallest of the heights to try another column that might be possibly taller
15            if (height[j] > height[i]) {
16                i++;
17            }
18            else {
19                j--;
20            }
21        }
22
23        return area;
24    }
25}

Want a walkthrough of this Java solution?

Get a step-by-step explanation of the idea behind the code.

All problems

Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.