Solution: 03/30/2014 Time Limit Exceeded
class Solution {
public:
int maxArea(vector &height) {
int maxArea = 0;
size_t n = height.size();
for(int i = 0; i < n; ++i) {
for(int j = i + 1; j < n; ++j) {
int shorter = std::min(height[i], height[j]);
int area = shorter * (j - i);
maxArea = area > maxArea ? area : maxArea;
}
}
return maxArea;
}
};
Modify, still Time Limit Exceeded, but gets better
class Solution {
public:
int maxArea(vector<int>& height) {
int maxArea = 0;
size_t n = height.size();
int maxLine = 0;
for(int i = 0; i < n; ++i) {
maxLine = height[i];
for(int j = i + 1; j < n; ++j) {
if(height[j] < maxLine) {
break;
}
int shorter = std::min(height[i], height[j]);
int area = shorter * (j - i);
if(area > maxArea) {
maxLine = height[j];
maxArea = area;
}
}
}
return maxArea;
}
};
Final working soltuion
class Solution {
public:
int maxArea(vector<int> &height) {
int maxArea = 0;
int n = height.size();
int start = 0, end = n - 1;
while(start < end) {
int water = std::min(height[start], height[end]) * (end - start);
maxArea = std::max(maxArea, water);
if(height[start] <= height[end]) {
start++;
} else {
end--;
}
}
return maxArea;
}
};
No comments:
Post a Comment