logo

Počítejte dílčí pole se součtem dělitelným K

Dané pole arr[] a celé číslo k úkolem je spočítat všechna podpole, jejichž součet je dělitelný k .

Příklady:

Vstup: arr[] = [450-2-31] k = 5
výstup: 7
Vysvětlení: Existuje 7 podpolí, jejichž součet je dělitelný 5: [4 5 0 -2 -3 1] [5] [5 0] [5 0 -2 -3] [0] [0 -2 -3] a [-2 -3].



bubble sort java

Vstup: arr[] = [2 2 2 2 2 2] k = 2
výstup: 21
Vysvětlení: Všechny součty dílčích polí jsou dělitelné 2.

Vstup: arr[] = [-1-3 2] k = 5
výstup:
Vysvětlení: Neexistuje žádné podpole, jehož součet je dělitelný k.

Obsah

[Naivní přístup] Iterace přes všechna dílčí pole

Smyslem je iterovat přes všechna možná podpole a přitom držet stopu součet podpole modulo k . Pro jakékoli podpole, pokud se podpole modulo k stane 0, zvyšte počet o 1. Po iteraci přes všechna podpole vraťte počet jako výsledek.

C++
// C++ Code to Count Subarrays With Sum Divisible By K // by iterating over all possible subarrays #include    #include  using namespace std; int subCount(vector<int> &arr int k) {  int n = arr.size() res = 0;     // Iterating over starting indices of subarray  for(int i = 0; i < n; i++) {  int sum = 0;    // Iterating over ending indices of subarray  for(int j = i; j < n; j++) {  sum = (sum + arr[j]) % k;  if(sum == 0)  res += 1;  }  }  return res; } int main() {  vector<int> arr = {4 5 0 -2 -3 1};  int k = 5;    cout << subCount(arr k); } 
C
// C Code to Count Subarrays With Sum Divisible By K // by iterating over all possible subarrays #include  int subCount(int arr[] int n int k) {  int res = 0;  // Iterating over starting indices of subarray  for (int i = 0; i < n; i++) {  int sum = 0;  // Iterating over ending indices of subarray  for (int j = i; j < n; j++) {  sum = (sum + arr[j]) % k;  if (sum == 0)  res += 1;  }  }  return res; } int main() {  int arr[] = {4 5 0 -2 -3 1};  int k = 5;  int n = sizeof(arr) / sizeof(arr[0]);  printf('%d' subCount(arr n k));  return 0; } 
Java
// Java Code to Count Subarrays With Sum Divisible By K // by iterating over all possible subarrays import java.util.*; class GfG {  static int subCount(int[] arr int k) {  int n = arr.length res = 0;  // Iterating over starting indices of subarray  for (int i = 0; i < n; i++) {  int sum = 0;  // Iterating over ending indices of subarray  for (int j = i; j < n; j++) {  sum = (sum + arr[j]) % k;  if (sum == 0)  res += 1;  }  }  return res;  }  public static void main(String[] args) {  int[] arr = {4 5 0 -2 -3 1};  int k = 5;  System.out.println(subCount(arr k));  } } 
Python
# Python Code to Count Subarrays With Sum Divisible By K # by iterating over all possible subarrays def subCount(arr k): n = len(arr) res = 0 # Iterating over starting indices of subarray for i in range(n): sum = 0 # Iterating over ending indices of subarray for j in range(i n): sum = (sum + arr[j]) % k if sum == 0: res += 1 return res if __name__ == '__main__': arr = [4 5 0 -2 -3 1] k = 5 print(subCount(arr k)) 
C#
// C# Code to Count Subarrays With Sum Divisible By K // by iterating over all possible subarrays using System; using System.Collections.Generic; class GfG {   static int subCount(int[] arr int k) {  int n = arr.Length res = 0;  // Iterating over starting indices of subarray  for (int i = 0; i < n; i++) {  int sum = 0;  // Iterating over ending indices of subarray  for (int j = i; j < n; j++) {  sum = (sum + arr[j]) % k;  if (sum == 0)  res += 1;  }  }  return res;  }  static void Main() {  int[] arr = { 4 5 0 -2 -3 1 };  int k = 5;  Console.WriteLine(subCount(arr k));  } } 
JavaScript
// JavaScript Code to Count Subarrays With Sum Divisible By K // by iterating over all possible subarrays function subCount(arr k) {  let n = arr.length res = 0;  // Iterating over starting indices of subarray  for (let i = 0; i < n; i++) {  let sum = 0;  // Iterating over ending indices of subarray  for (let j = i; j < n; j++) {  sum = (sum + arr[j]) % k;  if (sum === 0)  res += 1;  }  }  return res; } // Driver Code let arr = [4 5 0 -2 -3 1]; let k = 5; console.log(subCount(arr k)); 

Výstup
7

Časová náročnost: O(n^2), protože iterujeme přes všechny možné počáteční a koncové body podpolí.
Pomocný prostor: O(1)

zkratka všechna velká písmena excel

[Očekávaný přístup] Použití předpony Sum modulo k

Myšlenka je použít Technika předponového součtu spolu s Hašování . Při pozorném pozorování můžeme říci, že pokud má podpole arr[i...j] součet dělitelný k, pak (prefix sum[i] % k) se bude rovnat (prefix sum[j] % k). Můžeme tedy iterovat přes arr[] a zároveň udržovat hashovací mapu nebo slovník pro počítání počtu (prefix sum mod k). Pro každý index i bude počet podpolí končících na i a majících součet dělitelný k se rovnat počtu výskytů (prefix sum[i] mod k) před i.

Poznámka: Záporná hodnota (prefix sum mod k) musí být zpracována samostatně v jazycích jako C++ Jáva C# a JavaScript zatímco v Krajta (předpona součet mod k) je vždy nezáporná hodnota, protože přebírá znaménko dělitele, který je k .

C++
// C++ Code to Count Subarrays With Sum Divisible By K // using Prefix Sum and Hash map #include    #include  #include  using namespace std; int subCount(vector<int> &arr int k) {  int n = arr.size() res = 0;  unordered_map<int int> prefCnt;  int sum = 0;    // Iterate over all ending points  for(int i = 0; i < n; i++) {    // prefix sum mod k (handling negative prefix sum)  sum = ((sum + arr[i]) % k + k) % k;    // If sum == 0 then increment the result by 1  // to count subarray arr[0...i]  if(sum == 0)  res += 1;    // Add count of all starting points for index i  res += prefCnt[sum];    prefCnt[sum] += 1;  }  return res; } int main() {  vector<int> arr = {4 5 0 -2 -3 1};  int k = 5;    cout << subCount(arr k); } 
Java
// Java Code to Count Subarrays With Sum Divisible By K // using Prefix Sum and Hash map import java.util.*; class GfG {  static int subCount(int[] arr int k) {  int n = arr.length res = 0;  Map<Integer Integer> prefCnt = new HashMap<>();  int sum = 0;  // Iterate over all ending points  for (int i = 0; i < n; i++) {  // prefix sum mod k (handling negative prefix sum)  sum = ((sum + arr[i]) % k + k) % k;  // If sum == 0 then increment the result by 1  // to count subarray arr[0...i]  if (sum == 0)  res += 1;  // Add count of all starting points for index i  res += prefCnt.getOrDefault(sum 0);  prefCnt.put(sum prefCnt.getOrDefault(sum 0) + 1);  }  return res;  }  public static void main(String[] args) {  int[] arr = {4 5 0 -2 -3 1};  int k = 5;  System.out.println(subCount(arr k));  } } 
Python
# Python Code to Count Subarrays With Sum Divisible By K # using Prefix Sum and Dictionary from collections import defaultdict def subCount(arr k): n = len(arr) res = 0 prefCnt = defaultdict(int) sum = 0 # Iterate over all ending points for i in range(n): sum = (sum + arr[i]) % k # If sum == 0 then increment the result by 1 # to count subarray arr[0...i] if sum == 0: res += 1 # Add count of all starting points for index i res += prefCnt[sum] prefCnt[sum] += 1 return res if __name__ == '__main__': arr = [4 5 0 -2 -3 1] k = 5 print(subCount(arr k)) 
C#
// C# Code to Count Subarrays With Sum Divisible By K // using Prefix Sum and Hash map using System; using System.Collections.Generic; class GfG {  static int SubCount(int[] arr int k) {  int n = arr.Length res = 0;  Dictionary<int int> prefCnt = new Dictionary<int int>();  int sum = 0;  // Iterate over all ending points  for (int i = 0; i < n; i++) {    // prefix sum mod k (handling negative prefix sum)  sum = ((sum + arr[i]) % k + k) % k;  // If sum == 0 then increment the result by 1  // to count subarray arr[0...i]  if (sum == 0)  res += 1;  // Add count of all starting points for index i  if (prefCnt.ContainsKey(sum))  res += prefCnt[sum];  if (prefCnt.ContainsKey(sum))  prefCnt[sum] += 1;  else  prefCnt[sum] = 1;  }  return res;  }  static void Main() {  int[] arr = { 4 5 0 -2 -3 1 };  int k = 5;  Console.WriteLine(SubCount(arr k));  } } 
JavaScript
// JavaScript Code to Count Subarrays With Sum Divisible By K // using Prefix Sum and Hash map function subCount(arr k) {  let n = arr.length res = 0;  let prefCnt = new Map();  let sum = 0;  // Iterate over all ending points  for (let i = 0; i < n; i++) {  // prefix sum mod k (handling negative prefix sum)  sum = ((sum + arr[i]) % k + k) % k;  // If sum == 0 then increment the result by 1  // to count subarray arr[0...i]  if (sum === 0)  res += 1;  // Add count of all starting points for index i  res += (prefCnt.get(sum) || 0);  prefCnt.set(sum (prefCnt.get(sum) || 0) + 1);  }  return res; } // Driver Code let arr = [4 5 0 -2 -3 1]; let k = 5; console.log(subCount(arr k)); 

Výstup
7

Časová náročnost: O(n), protože přes pole iterujeme pouze jednou.
Pomocný prostor: O(min(n k)) jako nejvýše k klíče mohou být přítomny v hash mapě nebo slovníku.


Vytvořit kvíz