LC 974. Subarray Sums Divisible by K

Posted ethanhong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LC 974. Subarray Sums Divisible by K相关的知识,希望对你有一定的参考价值。

Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have a sum divisible by K.

 

Example 1:

Input: A = [4,5,0,-2,-3,1], K = 5
Output: 7
Explanation: There are 7 subarrays with a sum divisible by K = 5:
[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]

 

Note:

  1. 1 <= A.length <= 30000
  2. -10000 <= A[i] <= 10000
  3. 2 <= K <= 10000

用了dp,如果某一个数能被K整除,那么以该位结尾的这样的连续子数组的个数就是前一位dp值+1(新的1是它本身)。

如果不能被K整除,那么就让j从i开始往前遍历,碰到第一个从j到i能被K整除的子数组,那么该位上面的长度就是第j位的dp值加上1,新的1指的是从j到i的子数组。

class Solution {
public:
    int subarraysDivByK(vector<int>& A, int K) {
        vector<int> dp(A.size(),0);
        vector<int> Bsum(A.size()+1, 0);
        for(int i=0; i<A.size(); i++){
            Bsum[i+1] = Bsum[i] + A[i];
        }
        int ret = 0;
        for(int i=1; i<Bsum.size(); i++){
            if(A[i-1] % K == 0){
                if(i-1 == 0) dp[i-1] = 1;
                else dp[i-1] = dp[i-2] + 1;
                continue;
            }
            int newcnt = 0;
            for(int j=i-1; j>=0; j--){
                //if(Bsum[i] - Bsum[j] == 0) continue;
                if( (Bsum[i] - Bsum[j]) % K == 0) {
                    //cout << i << " " << j << endl;
                  newcnt += dp[j-1] + 1;
                  break;
                }
            }
            dp[i-1] = newcnt;
        }
        for(auto x : dp) ret += x;
        return ret;
    }
};

 

以上是关于LC 974. Subarray Sums Divisible by K的主要内容,如果未能解决你的问题,请参考以下文章

leetcode974. Subarray Sums Divisible by K

974. Subarray Sums Divisible by K. 前缀和同余定理

974. Subarray Sums Divisible by K. 前缀和同余定理

Leetcode 974. Subarray Sums Divisible by K

最大子段和DP前缀和C. Increase Subarray Sums

最大子段和DP前缀和C. Increase Subarray Sums