Skip to content

11. Container With Most Water

https://leetcode.com/problems/container-with-most-water/

js
/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function(height) {
  var result = 0
  var left = 0
  var right = height.length - 1

  while (left < right) {
    let area = Math.min(height[left], height[right]) * (right - left)
    result = Math.max(result, area)

    if (height[left] < height[right]) {
      let i = left
      while (i < right && height[i] <= height[left]) {
        i++
      }
      left = i
    } else {
      let i = right
      while (i > left && height[i] <= height[right]) {
        i--
      }
      right = i
    }
  }

  return result
}
py
class Solution(object):

    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        result = 0
        left, right = 0, len(height) - 1

        while left < right:
            area = min(height[left], height[right]) * (right - left)
            result = max(result, area)
            if height[left] < height[right]:
                i = left
                while i < right and height[i] <= height[left]:
                    i += 1
                left = i
            else:
                i = right
                while i > left and height[i] <= height[right]:
                    i -= 1
                right = i

        return result
go
func maxArea(height []int) int {
	result := 0
	left, right := 0, len(height)-1

	for left < right {
		area := min(height[left], height[right]) * (right - left)
		result = max(result, area)

		if height[left] < height[right] {
			i := left
			for i < right && height[i] <= height[left] {
				i++
			}
			left = i
		} else {
			i := right
			for i > left && height[i] <= height[right] {
				i--
			}
			right = i
		}
	}

	return result
}

func max(x int, y int) int {
	if x >= y {
		return x
	}
	return y
}

func min(x int, y int) int {
	if x <= y {
		return x
	}
	return y
}