前言
這題非要說貪心的話也算是吧,不過最主要的特徵還是雙指針。LC的題好像不少都是扔倆頭尾指針然後遍歷一遍完事兒的。這道題倒是“短板效應”的不錯體現了。
題目
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.
思路
圖片看不清楚的話可右鍵複製鏈接轉到圖牀再看。
代碼
class Solution {
public:
int maxArea(vector<int>& height) {
int first = 0;
int end = height.size() - 1;
int result = INT_MIN;
while (first < end)
{
int width = end - first;
int board = height[end]<height[first]?height[end]:height[first];
int area = board*width;
result = result>area?result:area;
if (height[first] <= height[end])
first++;
else
end--;
}
return result;
}
};