Tutorialspoint
Problem
Solution
Submissions

Container With Most Water

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 12

Write a C# program to solve the Container With Most Water problem. You are given an array of positive integers where each integer represents the height of a vertical line on a chart. Find two lines that together with the x-axis form a container that holds the most water. Return the maximum amount of water the container can hold.

Example 1
  • Input: height = [1,8,6,2,5,4,8,3,7]
  • Output: 49
  • Explanation: The maximum area is obtained by selecting the heights at indices 1 and 8 (heights 8 and 7), with a distance of 7 between them, giving an area of min(8, 7) * 7 = 7 * 7 = 49.
Example 2
  • Input: height = [4,3,2,1,4]
  • Output: 16
  • Explanation: The maximum area is obtained by selecting the heights at indices 0 and 4 (both height 4), with a distance of 4 between them, giving an area of min(4, 4) * 4 = 4 * 4 = 16.
Constraints
  • n == height.length
  • 2 ≤ n ≤ 10^5
  • 0 ≤ height[i] ≤ 10^4
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysControl StructuresLTIMindtreeD. E. Shaw
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • A brute force approach would be checking all pairs, but it would be O(n²)
  • Use the two-pointer technique for an optimal approach
  • Start with the widest possible container (pointers at both ends)
  • Move the pointer with the smaller height inward
  • Keep track of the maximum area seen so far

Steps to solve by this approach:

 Step 1: Initialize two pointers, left at the beginning and right at the end of the array.
 Step 2: Initialize a variable to keep track of the maximum area.
 Step 3: While left pointer is less than right pointer, calculate the current area.
 Step 4: The area is determined by the width (difference between indices) and the minimum height of the two lines.
 Step 5: Update the maximum area if the current area is greater.
 Step 6: Move the pointer that points to the smaller height inward, as this might lead to a larger area.
 Step 7: Return the maximum area found.

Submitted Code :