#K44892. Container With Most Water
Container With Most Water
Container With Most Water
You are given an array of n non-negative integers representing the height of vertical lines drawn on a coordinate plane. The width between each pair of neighboring lines is 1. Your task is to find two lines that together with the x-axis form a container such that the container contains the most water.
More formally, given an array h of length n, you need to choose two indices i and j with i < j such that the area of water contained is maximized. The area is given by the formula:
\( \text{Area} = (j - i) \times \min(h[i], h[j]) \)
Use the optimal two-pointer strategy to achieve a time complexity of \(O(n)\). If the array has fewer than two elements, no container can be formed, and the answer is 0.
inputFormat
The input is read from stdin as follows:
- The first line contains a single integer n which indicates the number of elements in the array.
- The second line contains n space-separated non-negative integers representing the heights of the vertical lines.
outputFormat
Print to stdout a single integer representing the maximum area of water that can be trapped between any two lines.
## sample9
1 8 6 2 5 4 8 3 7
49