BackmediumTwo Pointers TCS

Max Water Container Solution

Problem Statement

Given an array of integers representing the heights of silos, find the maximum volume of liquid that can be stored between any two silos.

Example 1
Input
[1,8,6,2,5,4,8,3,7]
Output
49

Explanation: Step-by-step: with input [1,8,6,2,5,4,8,3,7], we first initialize two pointers, one at the start and one at the end of the array. We then calculate the volume between the silos at positions 0 and 8, which is the minimum height (1) times the distance between them (8), giving a volume of 8. We then move the pointers towards each other, calculating the volume between the silos at positions 0 and 7, which is the minimum height (1) times the distance between them (7), giving a volume of 7. We continue this process until the pointers meet, resulting in a total volume of 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 = 36. However, we need to consider the silos at positions 0 and 8, which gives us a volume of 1 * 8 = 8. Therefore, the maximum volume of liquid that can be stored between any two silos is 49.

Example 2
Input
[1,1,1,1,1,1,1,1,1]
Output
0

Explanation: Step-by-step: with input [1,1,1,1,1,1,1,1,1], we first initialize two pointers, one at the start and one at the end of the array. We then calculate the volume between the silos at positions 0 and 8, which is the minimum height (1) times the distance between them (8), giving a volume of 8. However, since the minimum height is 1, the volume is 0. Therefore, the maximum volume of liquid that can be stored between any two silos is 0.

Constraints

  • 2 <= n <= 10^5
  • 0 <= heights[i] <= 10^4
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free