[leetcode] 1546. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target

Description

Given an array nums and an integer target.

Return the maximum number of non-empty non-overlapping subarrays such that the sum of values in each subarray is equal to target.

Example 1:

Input: nums = [1,1,1,1,1], target = 2
Output: 2
Explanation: There are 2 non-overlapping subarrays [1,1,1,1,1] with sum equals to target(2).

Example 2:

Input: nums = [-1,3,5,1,4,2,-9], target = 6
Output: 2
Explanation: There are 3 subarrays with sum equal to 6.
([5,1], [4,2], [3,5,1,4,2,-9]) but only the first 2 are non-overlapping.

Example 3:

Input: nums = [-2,6,6,3,5,4,1,2,8], target = 10
Output: 3

Example 4:

Input: nums = [0,0,0], target = 0
Output: 3

Constraints:

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 0 <= target <= 10^6

分析

题目的意思是:求等于target的非重叠子数组的个数。我一开始用双指针滑动窗口做了一下,发现不对,因为有负数。后面参考了一下别人的思路,用一个字典就可以解决了。

  • cur表示当前遍历的累积和,字典记录的是累积和的最后索引位置,然后就是遍历找符合条件的子数组了。

代码

class Solution:
    def maxNonOverlapping(self, nums: List[int], target: int) -> int:
        end=-1
        n=len(nums)
        cur=0
        res=0
        d={0:-1}
        for i in range(n):
            cur+=nums[i]
            t=cur-target
            if(t in d and d[t]+1>end):
                res+=1
                end=i
            d[cur]=i
                
        return res

参考文献

C++ 前缀和 + 哈希表优化 + 贪心选择
哈希+前缀和+动态规划

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值