11. Container With Most Water

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

思路

题目的意思就是计算两条线所围的面积,面积等于长乘以宽,要想让总面积变大,就要让二者尽可能的都大。所以可以从最长的宽开始计算,也就是一个数组的首尾,然后不断向里面挪,直到二者相遇,将过程中最大的面积输出即可。

挪动的策略就是,二者比较,谁短谁挪。

python3

class Solution:
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        left_idx, right_idx = 0, len(height) - 1
        area = 0
        while left_idx < right_idx:
            cur_area = min(height[left_idx], height[right_idx]) * (right_idx - left_idx)
            area = max(area, cur_area)
            if height[left_idx] < height[right_idx]:
                left_idx +=1
            else:
                right_idx -=1
        return area

c++11

class Solution {
public:
    int maxArea(vector<int>& height) {
        int area{0};
        auto left_idx = height.begin();
        auto right_idx = std::prev(height.end());
        while(left_idx < right_idx) {
            auto cur_area = std::min(*left_idx, *right_idx) * (right_idx - left_idx);
            area = std::max(area, static_cast<int>(cur_area));
            if(*left_idx < *right_idx)
                left_idx++;
            else
                right_idx--;
        }
        return area;
    }
};

results matching ""

    No results matching ""