Container With Most Water

https://leetcode.com/problems/container-with-most-water/description/

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.

Thoughts

[i, j]看作是当前问题的范围,假设i是短边,暴力解f_i(i+1, j)是对i遍历所有[i + 1, j], 因此f(i, j) = max(f_i(i+1, j), f(i + 1, j), fij), 但因为高度受限于i, f_i(i + 1, j)是一定小于fij的,因此可省去对i遍历所有[i + 1, j],问题范围缩小至[i + 1, j]。

Code

class Solution {
public:
    int maxArea(vector<int>& height) {
        int res = 0;
        for (int i = 0, j = height.size() - 1; i < j;) {
            res = max(res, min(height[i], height[j]) * (j - i));
            if (height[i] < height[j]) ++i; 
            else --j;
        }
        return res;
    }
};

Analysis

时间复杂度O(n). 空间O(1).

Last updated