首页 > 代码库 > Leetcode: Container With Most Water
Leetcode: Container With Most Water
The most strait forward approach is calculating all the possible areas and keep the max one as the result. This approach needs O(n*n) time complexity, which could not pass OJ (Time limit exceed).
There is so called "closing into the centre" approach. Idea of which is set two pointer at the start and end of the array (which I has thought about that), then move the shorter pointer each iteration. The idea be hide this movement is that if we move the longer line, no matter how many steps we move, the new area would be smaller than the one before movement. This is because area = (end-start)*min(height[start], height[end]) <- after move, (end-start) decrease, min(height[start], height[end]) remains no change, still the "shorter line".
1 public class Solution { 2 public int maxArea(int[] height) { 3 int res = 0; 4 int begin = 0, end = height.length - 1; 5 if (height.length == 0 || height.length == 1) return 0; 6 while (begin < end) { 7 if (height[begin] < height[end]) { 8 if (res < (end - begin) * height[begin]) { 9 res = (end - begin) * height[begin]; 10 } 11 begin++; 12 } 13 else { 14 if (res < (end - begin) * height[end]) { 15 res = (end - begin) * height[end]; 16 } 17 end--; 18 } 19 } 20 return res; 21 } 22 }