Program to find maximum number of non-overlapping subarrays with sum equals target using Python

PythonServer Side ProgrammingProgramming

Suppose we have an array nums and another value called target. Now we have to find the maximum number of non-empty non-overlapping subarrays such that the sum of values in each different subarray is same as target.

So, if the input is like nums = [3,2,4,5,2,1,5] target = 6, then the output will be 2 as there are two subarrays [2,4] and [1,5] whose sum is same as 6.

To solve this, we will follow these steps −

  • t := a new set with single element 0

  • temp := 0

  • ans:= 0

  • for each i in nums, do

    • temp := temp + i

    • prev := temp - target

    • if prev is in t, then

      • ans := ans + 1

      • t := a new set with single element temp

    • otherwise,

      • insert temp into t

  • return ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(nums, target):
   t = set([0])
   temp = 0
   ans=0
   for i in nums:
      temp += i
      prev = temp-target
      if prev in t:
         ans += 1
         t = set([temp])
      else:
         t.add(temp)
   return ans
nums = [3,2,4,5,2,1,5]
target = 6
print(solve(nums, target))

Input

"poput","vwput",9

Output

2
raja
Published on 28-May-2021 12:59:16
Advertisements