Leetcode 盛水最多的容器

在这里插入图片描述

算法思路:

Explanation:

  • Two-pointer technique:

    • Start with two pointers, one at the beginning (left) and one at the end (right) of the height array.
    • Calculate the area formed between the two vertical lines. The area is calculated as: Area = ( right − left ) × min ⁡ ( height[left] , height[right] ) \text{Area} = (\text{right} - \text{left}) \times \min(\text{height[left]}, \text{height[right]}) Area=(rightleft)×min(height[left],height[right])
    • Move the pointer that points to the shorter line inward (either left or right), as moving the shorter line has the potential to increase the maximum area.
    • Repeat this process until the two pointers meet.
  • Time Complexity:

    • The solution runs in O ( n ) O(n) O(n), where n n n is the number of elements in the height array, because each element is processed at most once.

代码:

class Solution {
public:
    int maxArea(vector<int>& height) {
        int left = 0;
        int right = height.size() - 1;
        int maxWater = 0;
        while(left < right) {
            int currentWater = (right - left) * min(height[left], height[right]);
            if(height[left] >= height[right]) {
                right--;
            }else {
                left++;
            }
            maxWater = max(maxWater, currentWater);
        }
        return maxWater;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值