ethan

ethan

新知,热爱生活,码农,读书
twitter
email
github

LCR 11. Container with the Most Water

Given an integer array height of length n. There are n vertical lines, with the two endpoints of the i-th line being (i, 0) and (i, height[i]). Find two lines among them that, together with the x-axis, form a container that can hold the maximum amount of water. Return the maximum amount of water that can be stored in the container.
Note: You cannot tilt the container.
image.png
Example 1:
Input: [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The vertical lines in the image represent the input array [1,8,6,2,5,4,8,3,7]. In this case, the container can hold the maximum amount of water (represented by the blue area), which is 49.
Example 2:
Input: height = [1,1]
Output: 1

Note:
n == height.length
2 <= n <= 105
0 <= height[i] <= 104

Solution 1: Two-pointer approach

func maxArea(height []int) int {
    left, right := 0,len(height)-1  // Define the left and right pointers, and determine the direction as moving towards the center
    water_level := 0
    for left < right { // Termination condition for moving towards the center
        w := right -left;
        h := min(height[left], height[right])
        water_level = max(water_level, w*h)
        if height[left]<height[right] { // Conditions for moving the left and right pointers
            left++
        }else {
            right--
        }
    }
    return water_level
}
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.