1. 程式人生 > >【LeetCode】LeetCode——第11題:Container With Most Water

【LeetCode】LeetCode——第11題:Container With Most Water

11. Container With Most Water

   My Submissions Total Accepted: 75667 Total Submissions: 219100 Difficulty: Medium

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i

 is at (iai) 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.

Subscribe to see which companies asked this question

Show Tags Show Similar Problems

題目的大概意思是:給定一些擋板,取兩個擋板使得蓄水量最大,並輸出最大蓄水量。當然,蓄水的高度由兩個擋板中較小者決定。

這道題難度等級:中等

看到這個題的第一反應就是用雙指標法,即l、r往中間靠攏,這裡的中間是泛指。

程式碼如下:

class Solution {
public:
    int maxArea(vector<int>& height) {
		int l = 0, r = height.size() - 1;
		int max_Area = 0;
		while (l < r){
			max_Area = max(max_Area, (r - l) * min(height[l], height[r]));
			height[l] > height[r] ? (r--) : (l++);
		}
		return max_Area;
    }
};

提交程式碼後順利AC掉,Runtime: 24 ms