算法 Java Leetcode Golang

Find a container which contains the most water.

Question

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 return 49.
Two Pointer ApproachTwo Pointer Approach

Note

  1. You may not slant the container.
  2. Brute Force approach may cause TLE.

Solution in Brute Force - TLE

  • java
1
2
3
4
5
6
7
8
9
10
11
public class Solution {
public int maxArea(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
public class Solution {
public int maxArea(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;
}
}