Leetcode Container With Most Water ,本算法的主要原理是从前两个方向进行扫描,保存最大的,并且在缩减范围,依据丢弃较小值的原则,相关cpp代码与测试如下:
#include<iostream>
#include<vector>
using namespace std;
// First we calculate the front till the end as the temporary value.
// And then we decrease the length of the array, by abandon the minimal of the
// two, because we can get the than: suppose the current length is m and the
// current V is "minimal * m", if we decrease the length of the container, we
// can never getting a lager result, so it is very wise to abandon the minimal
// value of the two.
class Solution {
public:
int maxArea(vector<int>& height) {
if (height.size() < 2) {
return 0;
}
int len = height.size();
int min = height[0] < height[len - 1]? height[0]: height[len - 1];
int re = min * (len - 1);
int low = 0;
int high= len - 1;
while (low < high) {
min = height[low] < height[high]? height[low] : height[high];
// Get the current higher value.
if (re < min * (high - low)) {
re = min * (high - low);
}
// Abandon the minimal value.
if (height[low] <= height[high]) {
low ++;
} else {
high --;
}
}
return re;
}
};
int main(int argc, char* argv[]) {
Solution so;
vector<int> test(4, 0);
test[0] = 3;
test[1] = 3;
test[2] = 1;
test[3] = 3;
int re = so.maxArea(test);
cout<<"result: "<<re<<endl;
return 0;
}