https://leetcode.com/problems/container-with-most-water/
题意:求最大矩形面积
思路:先假设最大的矩形由最左边和最右边的线段围成,如果想要继续扩大矩形面积,只有一个办法,那就是两边向中间收缩,同时我们想要改变的是值小的那条线,所以,每次都选择值小的那条边向中间进行收缩就行。
代码:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int maxArea(vector<int>& height) {
int l,r;
int M=0;
l=0,r=height.size()-1;
while(l<r)
{
M=max(M,min(height[l],height[r])*(r-l));
if(height[l]<height[r])
{
l++;
}
else{
r--;
}
}
return M;
}
};
反思:这题我一开始没想到那么精妙的算法,看了题解以后豁然开朗。