题目描述
给定一个数组,找到最大的面积,最大的长宽积。
一刷 暴力解法
class Solution {
public:
int maxArea(vector<int>& height) {
if(height.size()<2) return 0;
int h,k,temp;
int ans=0;
for(int i=1;i<height.size();i++){
for(int j=0;j<i;j++){
if(height[j]<height[i]) h = height[j];
else h = height[i];
k = i-j;
temp = h*k;
if(temp>ans) ans = temp;
}
}
return ans;
}
};
二刷 双指针
class Solution {
public:
int maxArea(vector<int>& height) {
if(height.size()<2) return 0;
int h,k;
double temp;
int ans=0;
int left = 0;
int right = height.size()-1;
while(left<right){
k = right-left;
if(height[left]<height[right]){
h = height[left];
temp = h*k;
if(temp>ans) ans = temp;
left++;
}
else{
h = height[right];
temp = h*k;
if(temp>ans) ans = temp;
right--;
}
}
return ans;
}
};