11 Container With Most Water
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate $$(i, a_i)$$. n vertical lines are drawn such that the two endpoints of line i is at $$(i, a_i)$$ and $$(i, 0)$$. Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Solution
class Solution {
public:
int maxArea(vector<int>& height) {
int n = height.size();
int i = 0, j = n-1;
int res = 0;
while ( i <= j-1 ) {
res = max(res, min(height[i], height[j])*(j-i));
if ( height[i] > height[j] ) j--;
else i++;
}
return res;
}
};
Notes
TODO: 严格证明解法的正确性!