forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request neetcode-gh#2323 from seinlin/523
Create 0523-continuous-subarray-sum.c
- Loading branch information
Showing
1 changed file
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
#define FREE_AND_RETURN(x, y) \ | ||
free(x); \ | ||
return y; | ||
|
||
bool checkSubarraySum(int* nums, int numsSize, int k){ | ||
unsigned int* sums = NULL; | ||
int i, 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); | ||
} |