53. Maximum Subarray (sliding window)

We know the subarray is a consecutive part of an array and this leads us to think about the two-pointer and sliding windows sort of algorithms.

As the question asks to find the maximum sum of the subarray. We consider using sliding windows which is a powerful algorithm (Time complexity: O(n), space complexity: O(1)).

The sliding window uses two pointers to support its operations. Usually, a left and a right pointer, the right pointer will keep moving forward and accumulate the sum at the same time. When you find something depreciating the value of the window, you would either move the left pointer forwardly or reset the window.

In this question, we call the sum of the window a local_max and call the answer a global_max.

If the right pointer moves forward found that the nums[right] would make local_max become negative. We would abandon this window and reset the left pointer to the right pointer, it is because the subarray is consecutive and you cannot skip this negative effect, so the only way to not carry this element is to find another subarray and that's why we reset the window.

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        //sliding window
        int local_max = 0, global_max = -1e9, r = 0, l = 0;
        while(r < nums.size()){
            local_max += nums[r];
            
            if(local_max > global_max){
                global_max = local_max;
            }
            if(local_max < 0){
                global_max = max(global_max, local_max);
                local_max = 0;
                l = r;
            }
            r++;
        }
        return global_max;   
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值