2014.2.8 21:37
Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container.
Solution:
A very plain solution is to do a O(n^2) scan, check out every pair of (a[i], a[j]) and find out the maximal min(a[i], a[j]) * (i - j).
You know this is far from satisfactory, so let's try to find an O(n) solution.
Suppose we've got a candidate pair (a[x], a[y]), the result is min(a[x], a[y]) * (x - y). If it is currently the optimal candidate, there cannot be any a[k] >= a[x] left of a[x], or any a[k] >= a[y] right of a[y], think about why.
If we are to find a better solution (a[x'], a[y']), it must lie within the interval (x, y), and satify the condition (a[x'] > a[x] && a[y'] >= a[y]) or (a[x'] >= a[x] && a[y'] > a[y]).
This means we can scan the array from both ends in one pass, and end the algorithm when both iteraotors meet in the middle.
Time complexity is O(n), space complexity is O(1).
Accepted code:
1 // 1CE, 1AC, good. 2 #include <algorithm> 3 using namespace std; 4 5 class Solution { 6 public: 7 int maxArea(vector<int> &height) { 8 if (height.empty()) { 9 return 0; 10 } 11 12 int ll, rr, kk, result; 13 14 ll = 0; 15 rr = (int)height.size() - 1; 16 result = 0; 17 while (ll < rr) { 18 result = max(result, min(height[ll], height[rr]) * (rr - ll)); 19 if (height[ll] < height[rr]) { 20 kk = ll + 1; 21 while (kk < rr && height[kk] <= height[ll]) { 22 ++kk; 23 } 24 ll = kk; 25 } else { 26 kk = rr - 1; 27 while (kk > ll && height[kk] <= height[rr]) { 28 --kk; 29 } 30 rr = kk; 31 } 32 } 33 34 return result; 35 } 36 };