Last active
October 25, 2019 05:01
-
-
Save yitonghe00/1cfa14c12e350f4d8a7b96141d2606e5 to your computer and use it in GitHub Desktop.
11. Container With Most Water (https://leetcode.com/problems/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 line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, suc…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Two pointer: begin/end pointers and move inward | |
// Time: O(n), 2ms | |
// Space: O(1), 39.9mb | |
class Solution { | |
public int maxArea(int[] height) { | |
int left = 0, right = height.length - 1; | |
int max = 0; | |
while(left < right) { | |
max = Math.max(max, Math.min(height[left], height[right]) * (right - left)); | |
// Move the lower side inside (proof by contradiction) | |
if(height[left] < height[right]) { | |
left++; | |
} else { | |
right--; | |
} | |
} | |
return max; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment