当前位置: 代码迷 >> 综合 >> LeetCode Container With Most Water Two Pointers (golang)
  详细解决方案

LeetCode Container With Most Water Two Pointers (golang)

热度:45   发布时间:2024-01-30 21:11:08.0

Problem
在这里插入图片描述
analytic process
The maximum yield depends on the second largest ordinate
Double pointer i j (i<j)is used to represent the head and tail of the array, and push forward until they meet
Calculate the current water load
area = (j-i) * min(height[i],height[j]
Then take the two Pointers with the lowest midpoint to the tail or head

code

func maxArea(height []int) int {maxArea := 0for i, j := 0, len(height)-1; i < j; {lower := Min(height[i], height[j])           //find a smaller coordinatemaxArea = Max((j-i)*lower, maxArea)          //calculate water loadfor height[i] <= lower && i < j {i++}                //if the current i ordinate is less than the smaller ordinate, the left pointer moves rightfor height[j] <= lower && i < j {j--}                //if the current j ordinate is less than the smaller ordinate, the right pointer moves left}return maxArea
}
func Max(a int, b int) int {if a > b {return a}return b
}
func Min(a int, b int) int {if a > b {return b}return a
}
  相关解决方案