贪心法,每个容器的面积取决于最短的木板,时间复杂度o(n),空间复杂度o(1)
class Solution {
public:
int maxArea(vector<int> &height) {
int start = 0;
int end = height.size() - 1;
int result = INT_MIN;
while (start < end) {
int area = min(height[end], height[start]) * (end - start);
result = max(result, area);
if (height[start] <= height[end]) {
start++;
} else {
end--;
}
}
return result;
}
};
本文介绍了一个经典的算法问题——容器盛水的最大容量问题,并提供了一种使用贪心算法解决该问题的方法。通过双指针从两端向中间逼近的方式,可以在O(n)的时间复杂度内找到最优解。
490

被折叠的 条评论
为什么被折叠?



