File tree 2 files changed +31
-0
lines changed
2 files changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def maxSubArrayLen (self , nums : List [int ], k : int ) -> int :
3
+ pref = [0 ] + list (accumulate (nums ))
4
+ two_sum = defaultdict (set ) # {difference val to k: [list of index sources]}
5
+
6
+ for i , x in enumerate (pref ) :
7
+ two_sum [k + x ].add (i )
8
+
9
+ output = 0
10
+ for i , x in enumerate (pref ) :
11
+ if x not in two_sum :
12
+ continue
13
+ for j in two_sum [x ] :
14
+ if j >= i :
15
+ continue
16
+ output = max (output , abs (i - j ))
17
+
18
+ return output
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def maxSubArrayLen (self , nums : List [int ], k : int ) -> int :
3
+ prev = {0 : - 1 }
4
+ output , curr_sum = 0 , 0
5
+
6
+ for i , x in enumerate (nums ) :
7
+ curr_sum += x
8
+ if curr_sum - k in prev : # Check prefix sum for possible k match
9
+ output = max (output , i - prev [curr_sum - k ])
10
+ if curr_sum not in prev : # First occurance will always be farthest / longest
11
+ prev [curr_sum ] = i
12
+
13
+ return output
You can’t perform that action at this time.
0 commit comments