Tutorialspoint
Problem
Solution
Submissions

Container With Most Water

Certification: Intermediate Level Accuracy: 0% Submissions: 1 Points: 10

Write a C program to find the container with the most water. Given n non-negative integers representing the heights of n vertical lines (or walls) placed at position 1, 2, ..., n, find two lines that, together with the x-axis, form a container that holds the most water.

Example 1
  • Input: height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
  • Output: 49
  • Explanation:
    • The container is formed by the two lines at positions 2 and 9.
    • Height of the left line is 8, height of the right line is 7.
    • The width of the container is 9 - 2 = 7.
    • The area of water the container can hold is min(8, 7) * 7 = 7 * 7 = 49.
Example 2
  • Input: height = [1, 1]
  • Output: 1
  • Explanation:
    • The container is formed by the two lines at positions 1 and 2.
    • Height of both lines is 1. The width of the container is 2 - 1 = 1.
    • The area of water the container can hold is min(1, 1) * 1 = 1 * 1 = 1
    .
Constraints
  • n == height.length
  • 2 <= n <= 10^5
  • 0 <= height[i] <= 10^4
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysNumberMicrosoftPwC
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

  • Use the two-pointer technique with one pointer at the beginning and one at the end
  • Calculate the area between the two pointers
  • Move the pointer pointing to the shorter line inward
  • Keep track of the maximum area seen so far
  • Continue until the two pointers meet

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: Calculate the area between the two lines as width (right - left) * minimum height of the two lines.
 Step 3: Update the maximum area if the current area is greater.
 Step 4: Move the pointer pointing to the shorter line inward (if equal, move either).
 Step 5: Repeat steps 2-4 until the two pointers meet.
 Step 6: Return the maximum area found.
 Step 7: This approach works because moving the pointer with the greater height inward would only decrease the area, as the width decreases and the height is still limited by the shorter line.

Submitted Code :