1. 程式人生 > >LC 974. Subarray Sums Divisible by K

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; } };