跳至主要內容

盛最多水的容器 (maxArea)

墨七leetcodeleetcode小于 1 分钟约 29 字...

盛最多水的容器 (maxArea)

https://leetcode.cn/problems/container-with-most-wateropen in new window


解法思路

Golang

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);
})();

上次编辑于:
贡献者: mo7
你认为这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
评论
  • 按正序
  • 按倒序
  • 按热度