统计和为 k 的子数组
在本教程中,我们将讨论一个程序,以查找和为 k 的子数组的数量。
为此,我们将提供一个数组和一个值 k。我们的任务是找出将总和作为给定值 k 的子数组数量。
示例
#include <bits/stdc++.h>
using namespace std;
//counting subarrays with k sum
int count_subarray(int arr[], int n, int k){
int mod[k];
memset(mod, 0, sizeof(mod));
int cumSum = 0;
for (int i = 0; i < n; i++) {
cumSum += arr[i];
//taking modulus to get positive sum
mod[((cumSum % k) + k) % k]++;
}
int result = 0;
for (int i = 0; i < k; i++)
if (mod[i] > 1)
result += (mod[i] * (mod[i] - 1)) / 2;
result += mod[0];
return result;
}
int main(){
int arr[] = { 4, 5, 0, -2, -3, 1 };
int k = 5;
int n = sizeof(arr) / sizeof(arr[0]);
cout << count_subarray(arr, n, k) << endl;
int arr1[] = { 4, 5, 0, -12, -23, 1 };
nt k1 = 5;
int n1 = sizeof(arr1) / sizeof(arr1[0]);
cout << count_subarray(arr1, n1, k1) << endl;
return 0;
}输出
7 7
广告
数据结构
联网
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP