Container With Most Water Problem Solution in Python

Day 15 of my Python learning journey: Today I tried a problem with a very interesting name. Problem: Container With Most Water The name itself made me curious. You are given an array where each element represents the height of a vertical line. You have to find two lines such that they form a container that can hold the maximum amount of water. Example: arr = [1,8,6,2,5,4,8,3,7] Output: 49 What I understood: The amount of water depends on: width (distance between two lines) height (minimum of the two lines) Water = width × min(height) Better approach (Two Pointer): Start one pointer from the left Start one pointer from the right Then: • Calculate area • Move the pointer with smaller height Code I wrote: arr = [1,8,6,2,5,4,8,3,7] left = 0 right = len(arr) - 1 max_area = 0 while left < right: width = right - left height = min(arr[left], arr[right]) area = width * height if area > max_area: max_area = area if arr[left] < arr[right]: left += 1 else: right -= 1 print(max_area) Problems I faced while coding this: At first I tried checking all pairs, which was too slow. I did not understand why we move the pointer with smaller height. It felt wrong to ignore some pairs, but the logic still worked. What I finally understood: Moving the smaller height pointer helps us try to find a better height while reducing width. This avoids unnecessary comparisons and makes the solution efficient. Time and Space Complexity: Time Complexity: O(n) Space Complexity: O(1) Question: Why do we always move the pointer with the smaller height? Today’s realization: Sometimes the best solution is not checking everything, but skipping the right things. #Python #DSA #Coding #Programming #LearningInPublic #100DaysOfCode #PythonProgramming

  • text

To view or add a comment, sign in

Explore content categories