Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water. See it on Leetcode
1
2
3
For example,
int[] a = { 1, 8, 6, 2, 5, 4, 8, 3, 7 },
it should return49.
Two Pointer Approach
Note
You may not slant the container.
Brute Force approach may cause TLE.
Solution in Brute Force - TLE
java
1 2 3 4 5 6 7 8 9 10 11
publicclassSolution{ publicintmaxArea(int[] height){ int n = height.length, maxArea = 0; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { maxArea = Math.max((j - i) * Math.min(height[i], height[j]), maxArea); } } return maxArea; } }
Solution in Java, C++ and Golang
java
cpp
go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
publicclassSolution{ publicintmaxArea(int[] height){ int maxArea = 0; int l = 0, r = height.length - 1; while (l < r) { maxArea = Math.max(maxArea, Math.min(height[l], height[r]) * (r - l)); if (height[l] < height[r]) { l++; } else { r--; } } return maxArea; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
class Solution { public: intmaxArea(vector<int>& height){ int maxArea = 0; int l = 0, r = height.size() - 1; while (l < r) { maxArea = fmax(maxArea, fmin(height[l], height[r]) * (r - l)); if (height[l] < height[r]) { l++; } else { r--; } } return maxArea; } };