×

Leetcode 11. Container With Most Water

96
SnailTyan
2018.07.05 10:14* 字数 39

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Container With Most Water

2. Solution

  • Brute Force
class Solution {
public:
    int maxArea(vector<int>& height) {
        int length = height.size();
        int maxArea = 0;
        int area = 0;
        for(int i = 0; i < length; i++) {
            for(int j = i + 1; j < length; j++) {
                area = (j - i) * (height[i]<height[j]?height[i]:height[j]);
                if(maxArea < area) {
                    maxArea = area;
                }
            }
        }
        return maxArea;
    }
};
  • Two Pointer Approach
class Solution {
public:
    int maxArea(vector<int>& height) {
        int i = 0;
        int j = height.size() - 1;
        int maxArea = 0;
        int area = 0;
        while(i < j) {
            area = (j - i) * (height[i]<height[j]?height[i]:height[j]);
            if(maxArea < area) {
                maxArea = area;
            }
            height[i]<height[j]?i++:j--;
        }
        return maxArea;
    }
};

参考资料

  1. https://leetcode.com/problems/container-with-most-water/description/
Leetcode
Web note ad 1