diff options
author | Jack Sangdahl <[email protected]> | 2025-03-10 00:36:13 -0600 |
---|---|---|
committer | Jack Sangdahl <[email protected]> | 2025-03-10 00:36:13 -0600 |
commit | 7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch) | |
tree | eb7a24ee2067f92245c57bb118e85a1baf15df50 /other/subarr_sum_divisible_k.cpp | |
parent | 5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff) | |
download | leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip |
chore: move cpp and rust code to directory
Diffstat (limited to 'other/subarr_sum_divisible_k.cpp')
-rw-r--r-- | other/subarr_sum_divisible_k.cpp | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/other/subarr_sum_divisible_k.cpp b/other/subarr_sum_divisible_k.cpp new file mode 100644 index 0000000..3661c96 --- /dev/null +++ b/other/subarr_sum_divisible_k.cpp @@ -0,0 +1,32 @@ +// 974. Subarray Sums Divisible by K +#include "leetcode.h" +#include <vector> + +/* + * given: integer array 'nums' and integer 'k' + * return: number of non-empty subarrays that + * have a sum divisible by 'k'. + * a subarray is a contiguous part of an array + */ + +class Solution { +public: + int subarraysDivByK(vector<int> &nums, int k) { + vector<int> count(k); + count[0] = 1; + int prefix = 0, ans = 0; + for (int i : nums) { + prefix = (prefix + i % k + k) % k; + ans += count[prefix]++; + } + return ans; + } +}; + +int main() { + Solution obj; + vector<int> nums1 = {4, 5, 0, -2, -3, 1}, nums2 = {5}; + cout << obj.subarraysDivByK(nums1, 5); // expect: 7 + cout << obj.subarraysDivByK(nums2, 9); // expect: 0 + return 0; +} |