Skip to content

Commit 072318a

Browse files
committed
Create 0523-continuous-subarray-sum.c
1 parent 303ea5b commit 072318a

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

c/0523-continuous-subarray-sum.c

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#define FREE_AND_RETURN(x, y) \
2+
free(x); \
3+
return y;
4+
5+
bool checkSubarraySum(int* nums, int numsSize, int k){
6+
unsigned int* sums = NULL;
7+
int i, j;
8+
9+
// Early return edge cases.
10+
if (numsSize < 2) {
11+
return false;
12+
}
13+
if (k == 1) {
14+
return true;
15+
}
16+
17+
sums = (unsigned int*)malloc(numsSize * sizeof(unsigned int));
18+
sums[0] = nums[0];
19+
for (i = 1; i < numsSize; i++) {
20+
// Return true, when there are two continuous nums are times of k.
21+
if (nums[i] % k == 0 && nums[i - 1] % k == 0) {
22+
FREE_AND_RETURN(sums, true);
23+
}
24+
25+
sums[i] = nums[i] + sums[i - 1];
26+
27+
// Return true, when the current subarray sum is times of k.
28+
if (sums[i] % k == 0) {
29+
FREE_AND_RETURN(sums, true);
30+
}
31+
}
32+
33+
for (i = 0; i < numsSize; i++) {
34+
if (sums[i] < k) {
35+
continue;
36+
}
37+
38+
for (j = 0; j < i - 1; j++) {
39+
// Return true, when the any subarray sum is times of k.
40+
if ((sums[i] - sums[j]) % k == 0) {
41+
FREE_AND_RETURN(sums, true);
42+
}
43+
}
44+
}
45+
46+
FREE_AND_RETURN(sums, false);
47+
}

0 commit comments

Comments
 (0)