forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0523-continuous-subarray-sum.c
47 lines (39 loc) · 1.13 KB
/
0523-continuous-subarray-sum.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#defineFREE_AND_RETURN(x, y) \
free(x); \
return y;
boolcheckSubarraySum(int*nums, intnumsSize, intk){
unsigned int*sums=NULL;
inti, j;
// Early return edge cases.
if (numsSize<2) {
return false;
}
if (k==1) {
return true;
}
sums= (unsigned int*)malloc(numsSize*sizeof(unsigned int));
sums[0] =nums[0];
for (i=1; i<numsSize; i++) {
// Return true, when there are two continuous nums are times of k.
if (nums[i] % k==0&&nums[i-1] % k==0) {
FREE_AND_RETURN(sums, true);
}
sums[i] =nums[i] +sums[i-1];
// Return true, when the current subarray sum is times of k.
if (sums[i] % k==0) {
FREE_AND_RETURN(sums, true);
}
}
for (i=0; i<numsSize; i++) {
if (sums[i] <k) {
continue;
}
for (j=0; j<i-1; j++) {
// Return true, when the any subarray sum is times of k.
if ((sums[i] -sums[j]) % k==0) {
FREE_AND_RETURN(sums, true);
}
}
}
FREE_AND_RETURN(sums, false);
}