2023年2月10日 星期五

11. Container With Most Water

解題思路

哪兩條直線能圍出最大面積?用 two pointer 分別指向兩端,慢慢往內縮求極值。

程式碼

class Solution {
public:
    int maxArea(vector<int>& height) {
        int left = 0, right = height.size() - 1;
        int maxA = 0, curA;
        while(left < right)
        {
            curA = min(height[left], height[right]) * (right - left);
            maxA = max(maxA, curA);
            if(height[left] < height[right])
                left++;
            else
                right--;            
        }
        return maxA;
    }
};

沒有留言:

張貼留言