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 and n is at least 2.
前天面試遇到的一道題,當着面試官的面沒有做出來,我當時想着類似於84. Largest Rectangle in Histogram的解法,沒想到是自己想太多。
這題是標準的雙指針類問題,使用兩個指針分別指向數組的頭和尾向中間遍歷(narrow down),每次只移動數值較小的指針,而且如果數值較小的指針向中間縮數值是遞減的,則直接跳過。
int maxArea(vector<int>& height)
{
int N = height.size();
int i = 0, j = N - 1;
int res = 0;
while (i < j)
{
int lower = height[i] < height[j] ? i : j;
res = max(res, height[lower] * (j - i));
// make the lower bar as large as possible in next step
// skip those decreasing numbers
if (lower == i)
for (i = i + 1; i < j && height[i] <= height[i - 1]; ++i);
else
for (j = j - 1; i < j && height[j] <= height[j + 1]; --j);
}
return res;
}
祝自己早日找到工作,乾巴爹!