添加鏈接描述
我的題解:
class Solution:def maxArea(self, height: List[int]) -> int:# 兩層for循環,保存最大值temp=0res=0for i in range(len(height)-1):for j in range(i+1,len(height)):temp=min(height[i],height[j])*(j-i)# print(temp)res=max(temp,res)return res
能出結果,但是超時了
class Solution:def maxArea(self, height: List[int]) -> int:left=0right=len(height)-1temp=0result=0while left<right:temp=min(height[left],height[right])*(right-left)result=max(result,temp)if height[left]<=height[right]:left+=1else:right-=1return result
這個題解的思路是:
因為ans=最小值(左邊,右邊)*距離(右邊-左邊)
無論如何這個距離都要減1,所以最小值這里就要取大值
那么如果左邊>右邊,右邊就向左邊移,這樣才能讓最小值增大
題解詳細描述