Container with Most Water

Container with Most Water – Hard Level Problem

You are given an array heights, where each element heights[i] represents the height of a vertical bar at position i. Your task is to select any two bars to form a container, with the width of the container being the distance between the two bars.

The goal is to find the maximum amount of water that this container can hold. Return the largest possible value of water that can be stored.

Container with Most Water

Constraints:

  • 2 <= height.length <= 1000
  • 0 <= height[i] <= 1000

Container with Most Water Solution

Recommendation for Time and Space Complexity –You should aim for a solution with O(n) time and O(1) space, where n is the size of the input array.

Hints for solving problems

Hint 1 :

A brute force solution would be to try all pairs of bars in the array, compute the water for each pair, and return the maximum water among all pairs. This would be an O(n^2) solution. Can you think of a better way?

Hint 2 :

Can you think of an algorithm that runs in linear time and is commonly used in problems that deal with pairs of numbers? Find a formula to calculate the amount of water when we fix two heights.

Hint 3 :

We can use the two pointer algorithm. One pointer is at the start and the other at the end. At each step, we calculate the amount of water using the formula (j – i) * min(heights[i], heights[j]). Then, we move the pointer that has the smaller height value. Can you think why we only move the pointer at smaller height?

Hint 4 :

In the formula, the amount of water depends only on the minimum height. Therefore, it is appropriate to replace the smaller height value.

There are mainly 2 approach to solve this problem-

  1. Brute Force Method
  2. Two Pointers Method

1. Brute Force Method

This approach involves checking the amount of water that can be stored between every possible pair of bars using nested loops. It has a time complexity of O(n²) and is simple but inefficient.

  • Time complexity: O(n^2)
  • Space complexity: O(1)

Code

2. Two Pointers Method

In this approach, two pointers are placed at the beginning and end of the array, and the water capacity is calculated while moving the pointers inward based on the smaller height. This method is more efficient with a time complexity of O(n).

  • Time complexity: O(n)
  • Space complexity: O(1)

Code

More Articles