nathanwailes

LeetCode 11 - Container With Most Water - 2023.10.10 solution

Oct 9th, 2023
1,224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.84 KB | None | 0 0
  1. class Solution:
  2.     def maxArea(self, height: List[int]) -> int:
  3.         """ Thought process: We want a smart way to test the different possible
  4.        combinations.  If we start with two pointers at the two ends of the
  5.        container, the question we should ask ourselves is: "What rule should we
  6.        follow to test new options intelligently?"  In this case, the leftmost
  7.        line is very short, while the rightmost line is very tall.  So the volume
  8.        is limited by the height of the shorter line.  Moving in the right pointer
  9.        will *never* be able to result in a larger volume than that initial volume
  10.        because the limitation was the *left* line.  So we should instead move in
  11.        the left pointer and see if we can get it to be a taller line.  So the
  12.        general rule seems to be: keep track of the indices and the volume of the
  13.        largest combination you've found so far, and then step inwards with the
  14.        pointer of the shorter line to see if you can find a taller line that would
  15.        make up for the loss of width with greater height.  When the two pointers
  16.        are pointing at the same line, stop and return whatever the best combination
  17.        was. [Update: We don't need the indices, just the volume.]
  18.  
  19.        I had a bug where my step conditional was comparing l and r instead of the
  20.        *heights* at l and r.
  21.        """
  22.         best_volume = 0
  23.  
  24.         l = 0
  25.         r = len(height) - 1
  26.  
  27.         while l < r:
  28.             current_container_height = min(height[l], height[r])
  29.             current_volume = (r - l) * current_container_height
  30.  
  31.             if current_volume > best_volume:
  32.                 best_volume = current_volume
  33.            
  34.             if height[l] > height[r]:
  35.                 r -= 1
  36.             else:
  37.                 l += 1
  38.         return best_volume
  39.  
Advertisement
Add Comment
Please, Sign In to add comment