11.盛最多水的容器
小于 1 分钟
11.盛最多水的容器
/*
* @lc app=leetcode.cn id=11 lang=typescript
*
* [11] 盛最多水的容器
*/
// @lc code=start
// 时间复杂度O(n^2),空间复杂度O(n)
// function maxArea(height: number[]): number {
// let max = 0;
// for (let i = 0; i < height.length; i++) {
// for (let j = i + 1; j < height.length; j++) {
// let area = (j-i)*Math.min(height[i],height[j])
// if(area>max){
// max = area
// }
// }
// }
// return max;
// }
function maxArea(height: number[]): number {
let l = 0,
r = height.length - 1;
let max = 0;
while (l < r) {
let area = (r - l) * Math.min(height[l], height[r]);
max = Math.max(max, area);
if (height[l] > height[r]) {
r--;
} else {
l++;
}
}
return max;
}
// @lc code=end
Loading...
