解题思路
利用双指针,从两边往中间走,每次选高的留下。这样一定会找到最优解
时间复杂度
遍历一次,时间复杂度$o(n)$
C++
class Solution {
public:
int maxArea(vector<int>& height) {
int res = 0;
for (int i = 0, j = height.size() - 1; i < j;) {
res = max(res, min(height[i], height[j]) * (j - i));
if (height[i] > height[j]) j--;
else i++;
}
return res;
}
};
Python3
class Solution:
def maxArea(self, height: List[int]) -> int:
i, j = 0, len(height) - 1
res = 0
while i < j :
res = max(res, min(height[i], height[j]) * (j - i))
if height[i] > height[j]: j -= 1
else: i += 1
return res
Go
func maxArea(height []int) int {
i, j := 0, len(height) - 1
res := 0
for i < j {
res = max(res, min(height[i], height[j]) * (j - i))
if height[i] > height[j] {
j--
}else{
i++
}
}
return res
}
func min(a int, b int) int {
if a > b {
return b
} else {
return a
}
}
func max(a int, b int) int {
if a > b {
return a
} else {
return b
}
}