Skip to content

Commit 12bad14

Browse files
authored
Create find-two-non-overlapping-sub-arrays-each-with-target-sum.py
1 parent eecb034 commit 12bad14

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
class Solution(object):
5+
def minSumOfLengths(self, arr, target):
6+
"""
7+
:type arr: List[int]
8+
:type target: int
9+
:rtype: int
10+
"""
11+
prefix, dp = {0: -1}, [float("inf")]*len(arr) # dp[i]: min len of target subarray until i
12+
result = min_len = float("inf")
13+
accu = 0
14+
for right in xrange(len(arr)):
15+
accu += arr[right]
16+
prefix[accu] = right
17+
if accu-target in prefix:
18+
left = prefix[accu-target]
19+
min_len = min(min_len, right-left)
20+
result = min(result, dp[left] + (right-left))
21+
dp[right] = min_len
22+
return result if result != float("inf") else -1

0 commit comments

Comments
 (0)