标签:
一开始使用动态规划来解决这道问题:
将可行解分为两类,一类为包含8号线,一类为不包含8号线;
将8号线依次与0~7号线配对,求出包含8号线的那一类可行解的最大值;
如果已经知道不包含8号线的最大值,即前七条线中的最大值,一个较小的子问题的解;
比较上两步中的最大值,即得结果。
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int maxArea(vector<int>& height) {
int length = height.size();
int *arr = new int[length];
arr[0] = 0;
arr[1] = min(height[0], height[1]) * 1;
for(int i = 2; i < height.size(); i++) {
int maxArea = 0;
for(int j = 0; j < i; j++) {
if(min(height[i], height[j]) * (i - j) > maxArea)
maxArea = min(height[i], height[j]) * (i - j);
}
if(maxArea > arr[i - 1])
arr[i] = maxArea;
else
arr[i] = arr[i - 1];
}
//for(int i = 0; i < height.size(); i++)
//cout << arr[i] << endl;
return arr[height.size() - 1];
}
};
int main() {
Solution solution;
vector<int> height;
height.push_back(3);height.push_back(2);height.push_back(5);height.push_back(3);
height.push_back(4);height.push_back(2);height.push_back(1);height.push_back(1);
//solution.maxArea(height);
cout << solution.maxArea(height) << endl;
getchar();
}
结果是超时,最后看到网上有o(n)的解法,其实不大看的懂,哈哈,代码如下:
class Solution {
public:
int maxArea(vector<int>& height) {
int left = 0;
int right = height.size() - 1;
int max = min(height[left], height[right]) * (right - left);
int tmp;
while(left < right) {
if(height[left] < height[right]) {
left++;
max = max > min(height[left], height[right]) * (right - left) ? max : min(height[left], height[right]) * (right - left);
}else {
right--;
max = max > min(height[left], height[right]) * (right - left) ? max : min(height[left], height[right]) * (right - left);
}
}
return max;
}
};
版权声明:本文为博主原创文章,未经博主允许不得转载。
LeetCode(11) Container With Most Water
标签:
原文地址:http://blog.csdn.net/guanzhongshan/article/details/46899411