题目
给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器,且 n 的值至少为 2。
示例:
输入: [1,8,6,2,5,4,8,3,7]
输出: 49
Swift解法
class Solution {
func maxArea(_ height: [Int]) -> Int {
var maxArea = 0
let sorted = height.enumerated().sorted { (lhs, rhs) -> Bool in
return lhs.element < rhs.element
}
var from = 0
var to = 0
for i in 0..<sorted.count {
if i != height.count - 1 {
if (sorted.count - 1) * sorted[i].element <= maxArea {
continue
}
from = Int.max
to = Int.min
for j in i..<sorted.count {
let offset = sorted[j].offset
if offset < from {
from = offset
}
if offset > to {
to = offset
}
}
if from < to {
maxArea = max(maxArea, (to - from) * sorted[i].element)
}
}
}
return maxArea
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/container-with-most-water