因此,复杂度为
O
(
n
)
O(n)
O(n) 的遍历即可
JAVA
import static java.lang.Integer.max;
// 如果不导入上面的类,下面则改为 Math.max()
class Solution {
public int maxArea(int[] height) {
int n = 0, m = height.length - 1, ans = 0;
while (n != m) {
ans = (height[n] < height[m]) ?
max(ans, (m - n) * height[n++]):
max(ans, (m - n) * height[m--]);
}
return ans;
}
}
Python
class Solution:
def maxArea(self, height: List[int]) -> int:
n, m, ans = 0, len(height)-1, 0
while n != m: # python 没有三元操作符
if height[n] < height[m]:
ans = max(ans, height[n] * (m - n)) # python 没有 n--只有 n -= 1
n += 1
else:
ans = max(ans, height[m] * (m - n))
m -= 1
return ans