- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

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

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

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

- Related Articles
- Program to find two non-overlapping sub-arrays each with target sum using Python
- Maximum Sum of Two Non-Overlapping Subarrays in C++
- Maximum Sum of 3 Non-Overlapping Subarrays in C++
- Program to find maximum number of non-overlapping substrings in Python
- Program to find maximum sum of two non-overlapping sublists in Python
- Maximum sum two non-overlapping subarrays of given size in C++
- Maximum sum of lengths of non-overlapping subarrays with k as the max element in C++
- Program to find sum of k non-overlapping sublists whose sum is maximum in C++
- Program to find largest sum of 3 non-overlapping sublists of same sum in Python
- Max sum of M non-overlapping subarrays of size K in C++
- Program to find number of sets of k-non-overlapping line segments in Python
- Find the Number of Subarrays with Odd Sum using C++
- Program to find minimum number of increments on subarrays to form a target array in Python
- Program to find number of sublists whose sum is given target in python
- Program to find number of distinct quadruple that forms target sum in python

Advertisements