1
- def maxSubArrayLen (nums , k ):
1
+ #Question: Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn't one, return 0 instead.
2
+ #Solution: Keep a hashmap of sums up to that point
3
+ #Difficulty: Medium
4
+ #Space Complexity: O(n)
5
+ #Time Complexity: O(n)
6
+
7
+ from typing import List
8
+
9
+ def maxSubArrayLen (nums : List [int ], k : int ):
10
+ #Initialize values for the max sub-array itself and it's value
2
11
answer , accumulator = [], 0
3
- sumMap = {0 :- 1 }
4
- for i ,v in enumerate (nums ):
12
+
13
+ #Create a hashmap with keys being sums and values indexes, sum at index -1 is 0
14
+ #This is important because if the accumulator sums to 0 at any point we can use this 0 and include all numbers from the beginning
15
+ sumMap = {0 : - 1 }
16
+
17
+ for i , v in enumerate (nums ):
18
+ #Increment the accumulator by the number in the array
5
19
accumulator += v
20
+
21
+ #If we haven't previously encountered this number, add it to hashmap with index i
6
22
if accumulator not in sumMap : sumMap [accumulator ] = i
7
- print (sumMap , accumulator - k )
8
- if accumulator - k in sumMap :
9
- if (i - sumMap [accumulator - k ]) > len (answer ): answer = nums [sumMap [accumulator - k ]+ 1 :i + 1 ]
23
+
24
+ #If the accumulator - the k we're looking for happens to be in our map
25
+ #This is because accumulator - (accumulator - k) = k. In other words the accumulator up to this point, subtracted by the (accumulator-k) must be k
26
+ if accumulator - k in sumMap :
27
+
28
+ #If the length of k is greater than the length of our answer, because k spans from index at sum accumulator - k to index at i (from the above comment)
29
+ if (i - sumMap [accumulator - k ]) > len (answer ):
30
+
31
+ #Set answer to be the subarray starting from the inde of the sum (accumulator-k) to i inclusively
32
+ #We want the starting point to be non-inclusive of the last item in the sum (accumulator-k) because we need to subtract this sum completely...
33
+ #..from the current accumulator in order to obtain k. (Since accumulator - (accumulator - k) = k)
34
+ answer = nums [sumMap [accumulator - k ]+ 1 :i + 1 ]
10
35
return answer
11
36
12
37
13
38
def main ():
39
+ print (maxSubArrayLen ([1 , 1 , 2 , 3 , - 1 , 0 , - 1 , 1 , 2 , 3 ], 5 ))
14
40
print (maxSubArrayLen ([- 2 , - 1 , 2 , 1 , 9 ], 9 ))
15
41
main ()
0 commit comments