Leetcode - 11. Container With Most Water
Leetcode - 11. Container With Most Water
You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container can store.
Notice that you may not slant the container.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
func maxArea(height []int) int {
leftH, rightH := 0, len(height)-1
maxWater := 0
for leftH<rightH{
if height[leftH]<height[rightH]{
area := (rightH-leftH)*height[leftH]
if area>maxWater{
maxWater = area
}
leftH++
}else{
area := (rightH-leftH)*height[rightH]
if area>maxWater{
maxWater = area
}
rightH--
}
}
return maxWater
}
This post is licensed under CC BY 4.0 by the author.