盛最多水的容器 (maxArea)
2024/11/27小于 1 分钟约 27 字...
盛最多水的容器 (maxArea)
https://leetcode.cn/problems/container-with-most-water
解法思路
Golang
//go:build ignore
package main
import (
	"fmt"
)
func main() {
	nums := []int{
		1, 8, 6, 2, 5, 4, 8, 3, 7,
	}
	results := maxArea(nums)
	fmt.Println("results", results)
}
// 暴力求解
/*
计算最大容积
容积的公式为 底*高
底 = 当前下标和未来下标的差
高 = 二者之间最大值
*/
func maxArea(height []int) int {
	res := 0             // 最大面积
	l := 0               // 最左边
	r := len(height) - 1 // 最右边
	for l < r {
		y := 0
		x := r - l
		if height[l] < height[r] {
			y = height[l]
			l++
		} else {
			y = height[r]
			r--
		}
		are := y * x
		if are > res {
			res = are
		}
	}
	return res
}
JavaScript
// 暴力求解
var maxArea = function (nums) {};
// 代码执行块
(function () {
  const nums = [1, 2, 0, 3, 4, 0, 1, 0, 5, 0];
  const result = maxArea(nums);
  console.log('result', result);
})();
