Container with Most Water šŸŽÆ

beginner
9 min

Container with Most Water šŸŽÆ

Welcome to our comprehensive guide on the popular problem called "Container with Most Water"! This problem is a great way to understand and practice Data Structures and Algorithms, especially the concept of Two Pointers algorithm. Let's dive in!

Understanding the Problem šŸ“

In this problem, we are given a list of n heights (numbers) representing the height of the containers. The goal is to find the maximum amount of water that can be held by two adjacent containers.

Here's an example to help illustrate:

Input: heights = [1, 8, 6, 2, 5, 4, 8, 3, 7] Output: 49 (Maximum water is between containers at indices 1 and 8)

Let's Solve It! šŸ’”

We can solve this problem using the Two Pointers algorithm. The idea is to use two pointers, left and right, to traverse the list from both ends. The maximum water volume is found when left's height is multiplied by the distance between left and right.

python
def max_water(heights): left = 0 right = len(heights) - 1 max_water = 0 while left < right: # Find the minimum height between left and right min_height = min(heights[left], heights[right]) # Calculate the water volume water_volume = min_height * (right - left) # If the current water volume is more than the maximum water, update it if water_volume > max_water: max_water = water_volume # Move the left pointer to the right if there's a chance for more water if heights[left] < heights[right]: left += 1 # Move the right pointer to the left if there's a chance for more water else: right -= 1 return max_water

Putting It All Together āœ…

Now that you understand the problem and the solution, let's put it all together and find the maximum amount of water that can be held by two adjacent containers in the given list:

python
heights = [1, 8, 6, 2, 5, 4, 8, 3, 7] print(max_water(heights)) # Output: 49

:::quiz Question: What is the maximum amount of water that can be held by two adjacent containers in the given list [1, 8, 6, 2, 5, 4, 8, 3, 7]? A: 16 B: 30 C: 49 Correct: C Explanation: The maximum water is between containers at indices 1 and 8, where the height of the containers is 1 and 8, respectively. The maximum water volume is 1 * (8 - 1) = 49.