https://leetcode.cn/problems/container-with-most-water/description/?envType=study-plan-v2&envId=top-interview-150

 

package leetcode150

import "testing"

func TestMaxArea(t *testing.T) {
    height := []int{1, 8, 6, 2, 5, 4, 8, 3, 7}
    res := maxArea2(height)
    println(res)
}

func maxArea2(height []int) int {
    i, j := 0, len(height)-1
    sumMax := 0
    for i < j {
        h := min(height[i], height[j])
        if sumMax < (j-i)*h {
            sumMax = (j - i) * h
        }

        if height[i] > height[j] {
            j--
        } else {
            i++
        }
    }
    return sumMax
}

func maxArea(height []int) int {
    if len(height) < 2 {
        return 0
    }
    sumMax := 0
    for i := 0; i < len(height); i++ {
        curMaxHeight := -1
        for j := len(height) - 1; j > i; j-- {
            if curMaxHeight > height[j] {
                continue
            } else {
                curMaxHeight = height[j]
            }
            if sumMax < (j-i)*min(height[j], height[i]) {
                sumMax = (j - i) * min(height[j], height[i])
            }
            if curMaxHeight >= height[i] {
                break
            }
        }
    }
    return sumMax
}

func min(a, b int) int {
    if a > b {
        return b
    }
    return a
}