Contents

LeetCode 11. Container With Most Water

11.ContainerWithMostWater.py

from typing import List


class Solution:
    def maxArea(self, height: List[int]) -> int:
        maxArea = 0
        left, right = 0, len(height) - 1
        while left < right:
            currentArea = (right - left) * min(height[left], height[right])
            maxArea = max(currentArea, maxArea)
            if height[left] < height[right]:
                left += 1
            else:
                right -= 1
        return maxArea


if __name__ == '__main__':
    sol = Solution()
    assert sol.maxArea(height=[1, 8, 6, 2, 5, 4, 8, 3, 7]) == 49
    assert sol.maxArea(height=[1, 1]) == 1

lc11ContainerWithMostWater_test.go

package lc

import (
	"testing"
)

func maxArea(height []int) int {
	maxArea := 0
	left, right := 0, len(height)-1
	for left < right {
		currentArea := (right - left) * min(height[left], height[right])
		maxArea = max(currentArea, maxArea)
		if height[left] < height[right] {
			left++
		} else {
			right--
		}
	}
	return maxArea
}

func TestMaxArea(t *testing.T) {
	tests := []struct {
		height []int
		want   int
	}{
		{[]int{1, 8, 6, 2, 5, 4, 8, 3, 7}, 49},
		{[]int{1, 1}, 1},
	}

	for _, test := range tests {
		got := maxArea(test.height)
		if got != test.want {
			t.Errorf("maxArea(%v) = %v; want %v", test.height, got, test.want)
		}
	}
}