ZhongKuo0228 / study

0 stars 0 forks source link

11. Container With Most Water #70

Open fockspaces opened 10 months ago

fockspaces commented 10 months ago
  1. l, r 雙指針
  2. 從最外圍開始算,每次都往較低的牆內縮一格
class Solution:
    def maxArea(self, height: List[int]) -> int:
        l, r, ans = 0, len(height) - 1, 0
        while l < r:
            width = r - l
            cup_height = min(height[r], height[l])
            ans = max(ans, cup_height * width)
            if height[l] < height[r]:
                l += 1
            else:
                r -= 1
        return ans
fockspaces commented 7 months ago

greedy + two pointers: determine the searching direction, update ans in each iteration.

class Solution:
    def maxArea(self, height: List[int]) -> int:
        l, r = 0, len(height) - 1
        ans = 0
        while l < r:
            amount = (r - l) * min(height[l], height[r])
            ans = max(ans, amount)
            if height[l] < height[r]:
                l += 1
            else:
                r -= 1
        return ans