Skip to content

Commit 9bcb2c2

Browse files
Update FindTwoNonOverlappingSubarraysWithTargetSum.py
1 parent 323715d commit 9bcb2c2

File tree

1 file changed

+10
-5
lines changed

1 file changed

+10
-5
lines changed

Python/PriorityQueue/FindTwoNonOverlappingSubarraysWithTargetSum.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ def minSumOfLengths(self, arr: List[int], target: int) -> int:
1313
return -1
1414

1515
slidingWindowSum = 0
16-
minLengthEndingBefore = float('inf')
16+
minLengthEndingBefore = [float('inf') for i in range(len(arr))]
1717
start = 0
1818
result = float('inf')
1919
for end in range(len(arr)):
@@ -25,10 +25,12 @@ def minSumOfLengths(self, arr: List[int], target: int) -> int:
2525
if slidingWindowSum == target:
2626
currSubarrayLen = end - start + 1
2727
if minLengthEndingBefore != float('inf'):
28-
result = min(result, currSubarrayLen + minLengthEndingBefore)
29-
minLengthEndingBefore = min(minLengthEndingBefore, currSubarrayLen)
30-
else:
31-
continue
28+
if start - 1 >= 0:
29+
result = min(result, currSubarrayLen + minLengthEndingBefore[start-1])
30+
minLengthEndingBefore[end] = min(minLengthEndingBefore[end], currSubarrayLen)
31+
32+
if end >= 1:
33+
minLengthEndingBefore[end] = min(minLengthEndingBefore[end - 1], minLengthEndingBefore[end])
3234

3335
return result if result != float('inf') else -1
3436

@@ -39,5 +41,8 @@ def test_Leetcode(self):
3941
self.assertEqual(-1, self.minSumOfLengths([5, 5, 4, 4, 5], 3))
4042
self.assertEqual(3, self.minSumOfLengths([3, 1, 1, 1, 5, 1, 2, 1], 3))
4143

44+
def test_Wrongcase(self):
45+
self.assertEqual(-1, self.minSumOfLengths([1, 6, 1], 7))
46+
4247
if __name__ == '__main__':
4348
unittest.main()

0 commit comments

Comments
 (0)