File tree 1 file changed +16
-24
lines changed
scripts/algorithms/M/Make Sum Divisible by P
1 file changed +16
-24
lines changed Original file line number Diff line number Diff line change 1
- # Runtime: 824 ms (Top 50.97%) | Memory: 32.5 MB (Top 61.17%)
1
+ // Runtime : 457 ms (Top 46.03 % ) | Memory : 34.70 MB (Top 85.36 % )
2
+
2
3
class Solution :
3
4
def minSubarray (self , nums : List [int ], p : int ) -> int :
4
- r = sum (nums )% p
5
- if r == 0 : return 0
6
-
7
- d = {0 :- 1 }
8
- s = 0
9
- ans = None
10
-
11
- for i , n in enumerate (nums ):
12
- s = (s + n )% p
13
-
14
- # save all possible remainder with latest index only
15
- d [s ] = i
16
-
17
- # search the target remainder with index closest to current i
18
- # s is the current remainder so we can derive such relation:
19
- # s - target = r (mod p) => target = s-r (mod p)
20
- target = (s - r )% p
21
- if target in d :
22
- a = i - d [target ]
23
- if ans is None : ans = a
24
- else : ans = min (ans , a )
25
- if ans == len (nums ) or ans is None : return - 1
26
- return ans
5
+ n = len (nums )
6
+ target = sum (nums )% p
7
+ if not target :
8
+ return 0
9
+ answer = n
10
+ prefix_sum = 0
11
+ hashmap = {0 : - 1 }
12
+ for i , num in enumerate (nums ):
13
+ prefix_sum += num
14
+ key = (prefix_sum % p - target )% p
15
+ if key in hashmap :
16
+ answer = min (answer , i - hashmap [key ])
17
+ hashmap [prefix_sum % p ] = i
18
+ return answer if answer < n else - 1
You can’t perform that action at this time.
0 commit comments