Skip to content
Rain Hu's Workspace
Go back

[Leetcode] 11. Container With Most Water

Rain Hu

11. Container With Most Water


一、題目

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
Find two lines that together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container can store.
Notive that you may not slant the container.

Example 1:
question_11

Example 2:

Constraints:


二、分析

三、解題

1. Two Pointer

int calArea(vector<int>& height, int left, int right) {
    return min(height[left], height[right]) * (right - left);
}
int maxArea(vector<int>& height) {
    int left = 0, right = height.size()-1;
    int res = 0;
    do {
        res = max(res, calArea(height, left, right));
        if (height[left] < height[right])
            left++;
        else 
            right--;
    } while (left < right);
    return res;

}

回目錄 Catalog


Share this post on:

Previous
[Leetcode] 12. Integer to Roman
Next
[Leetcode] 10. Regular Expression Matching