[LeetCode #11] Container With Most Water
2016-10-01 21:44 amadis 阅读(113) 评论(0) 编辑 收藏 举报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.
Note: You may not slant the container.
1 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y)) 2 3 int maxArea(int* height, int heightSize) { 4 int left = 0; 5 int right = heightSize - 1; 6 int max = 0; 7 int cur = 0; 8 9 if (heightSize < 2){ 10 return 0; 11 } 12 13 while(left < right){ 14 cur = (right - left) * MIN(height[left], height[right]); 15 if (cur > max){ 16 max = cur; 17 } 18 if (height[right] < height[left]){ 19 right--; 20 }else if (height[right] > height[left]){ 21 left++; 22 }else{ 23 left++; 24 right--; 25 } 26 } 27 28 return max; 29 }