Posted on

Description

Submission

class Solution {
public:
    int subarraysDivByK(vector<int>& nums, int k) {
        int n = nums.size();
        int sum = 0;
        vector<int> count(k, 0);
        count[0] = 1;
        for(int i = 0; i < n; ++i) {
            if(nums[i] < 0) {
                nums[i] += (-nums[i] / k + 1) * k;
            }
            sum += nums[i];
            sum %= k;
            ++count[sum];
        }
        int ret = 0;
        for(auto x: count) {
            ret += x * (x - 1) / 2;
        }
        return ret;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *