Skip to content

Latest commit

 

History

History
45 lines (34 loc) · 1.41 KB

0011. 盛最多水的容器 [Medium] [Container With Most Water].md

File metadata and controls

45 lines (34 loc) · 1.41 KB

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.

img

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

题目

思路:双指针。

工程代码下载

class Solution {
public:
    int maxArea(vector<int>& height) {
        int res = 0;
        int n = height.size();
        int i = 0, j = n - 1;
        while(i < j){
            int area = min(height[i], height[j]) * (j - i);
            res = max(res, area);
            // 移动短边。因为移动长边的话,宽度变小,而最小高度只可能不变或变小,导致面积只会更小。
            if(height[i] < height[j])
                ++i;
            else
                --j;
        }
        return res;
    }
};