This is a place to put my clutters, no matter you like it or not, welcome here.
0%
11. Container With Most Water
Posted onEdited onIn面試Views: Symbols count in article: 1.9kReading time ≈2 mins.
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.
Example 1:
1 2 3
Input: height = [1,8,6,2,5,4,8,3,7] Output: 49 Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
public class Solution { public int maxArea(int[] height) { int res = 0, l = 0, r = height.length - 1; while (l < r) { res = Math.max(res, Math.min(height[l], height[r]) * (r - l)); if (height[l] < height[r]) ++l; else --r; } return res; } }
Python
Point to the beggining and the end of the list
Look for the smallest number out of these pointers
Calculate area
Move pointer from the lowest because we’re always looking for the largest area
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Time: O(n), Space: O(1)
class Solution: def maxArea(self, height: List[int]) -> int: hisArea = 0 l, r= 0, len(height)-1 while l<r: h = min(height[l],height[r]) area = h*(r-l) hisArea = max(hisArea,area) # compare last and now if height[l] < height[r]: l+=1 else: r-=1 return hisArea
public class Solution { public int trap(int[] height) { int res = 0, l = 0, r = height.length - 1; while (l < r) { int mn = Math.min(height[l], height[r]); if (height[l] == mn) { ++l; while (l < r && height[l] < mn) { res += mn - height[l++]; } } else { --r; while (l < r && height[r] < mn) { res += mn - height[r--]; } } } return res; } }