11. Container With Most Water
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 the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.
Notice that you may not slant the container.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 class Solution {public : int maxArea (vector<int >& height) { int answer = 0 , minHeight = height[0 ]; bool isChecked[30002 ] = {false , }; for (int i = 1 ; i < height.size (); i++) { answer = max (answer, i * min (height[0 ], height[i])); } isChecked[height[0 ]] = isChecked[0 ] = true ; for (int i = 1 ; i < height.size (); isChecked[height[i++]] = true ) { if (isChecked[height[i]] || height[i] <= minHeight) continue ; minHeight = height[i]; for (int j = height.size () - 1 ; j >= i + (answer / height[i]); j--) { answer = max (answer, (j - i) * min (height[i], height[j])); } } return answer; } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Solution {public : int maxArea (vector<int >& height) { int answer = 0 , head = 0 , tail = height.size () - 1 ; while (head != tail) { answer = max (answer, (tail - head) * min (height[tail], height[head])); if (height[head] <= height[tail]) head++; else tail--; } return answer; } };