11. Maximum Number of Non-Overlapping Subarrays With Sum Equals Target

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

Solution:

Approach: Use prefix sum to check for all subarray with target sum Greedly check for maxEnd to prevent non overlapping intervals

class Solution
{
public:
    int maxNonOverlapping(vector<int> &nums, int target)
    {

        vector<int> preSum;
        unordered_map<int, int> m;

        int s = 0;
        for (int i = 0; i < nums.size(); i++)
        {
            s = s + nums[i];
            preSum.push_back(s);
        }

        m[0] = -1;
        int maxEnd = -1;
        int count = 0;

        for (int i = 0; i < preSum.size(); i++)
        {

            int val = preSum[i] - target;

            if (m.find(val) != m.end())
            {
                if (m[val] >= maxEnd)
                {
                    maxEnd = i;
                    count++;
                }
            }
            m[preSum[i]] = i;
        }

        return count;
    }
};

Time Complexity: O(n) Space Complexity: O(n)

Last updated