- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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 −

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))

"poput","vwput",9

2

- Related Questions & Answers
- Maximum Sum of 3 Non-Overlapping Subarrays in C++
- Maximum Sum of Two Non-Overlapping Subarrays in C++
- Program to find two non-overlapping sub-arrays each with target sum using 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++
- Find number of subarrays with even sum in C++
- 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
- Program to find maximum sum of non-adjacent nodes of a tree in Python
- Program to find sum of contiguous sublist with maximum sum in Python
- Number of Dice Rolls With Target Sum in Python

Advertisements