hello-algo/codes/go/chapter_greedy/max_capacity.go
Yudong Jin f68bbb0d59
Update the book based on the revised second edition (#1014)
* Revised the book

* Update the book with the second revised edition

* Revise base on the manuscript of the first edition
2023-12-28 18:06:09 +08:00

28 lines
594 B
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// File: max_capacity.go
// Created Time: 2023-07-23
// Author: Reanon (793584285@qq.com)
package chapter_greedy
import "math"
/* 最大容量:贪心 */
func maxCapacity(ht []int) int {
// 初始化 i, j使其分列数组两端
i, j := 0, len(ht)-1
// 初始最大容量为 0
res := 0
// 循环贪心选择,直至两板相遇
for i < j {
// 更新最大容量
capacity := int(math.Min(float64(ht[i]), float64(ht[j]))) * (j - i)
res = int(math.Max(float64(res), float64(capacity)))
// 向内移动短板
if ht[i] < ht[j] {
i++
} else {
j--
}
}
return res
}