Dada una array arr , la tarea es encontrar el número total de subarreglos de la array dada que no contienen ningún subarreglo cuya suma de elementos sea igual a cero. Todos los elementos de la array son distintos.
Ejemplos:
Entrada: arr = {2, 4, -6}
Salida: 5
Explicación:
Hay 5 subarreglos que no contienen ningún subarreglo cuya suma de elementos sea igual a cero: [2], [4], [-6], [2 , 4], [4, -6]
Entrada: array = {10, -10, 10}
Salida: 3
Acercarse:
- En primer lugar, almacene todos los elementos de la array como suma de su elemento anterior.
- Ahora tome dos punteros, aumente el segundo puntero y almacene el valor en un mapa mientras no se encuentra un mismo elemento.
- Si se encuentra un elemento que ya existe en el mapa, esto significa que existe un subarreglo entre dos punteros cuya suma de elementos es igual a 0.
- Ahora aumente el primer puntero y elimine el elemento del mapa mientras existan los dos mismos elementos.
- Almacene la respuesta en una variable y finalmente devuélvala.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program to Count the no of subarray // which do not contain any subarray // whose sum of elements is equal to zero #include <bits/stdc++.h> using namespace std; // Function that print the number of // subarrays which do not contain any subarray // whose elements sum is equal to 0 void numberOfSubarrays(int arr[], int n) { vector<int> v(n + 1); v[0] = 0; // Storing each element as sum // of its previous element for (int i = 0; i < n; i++) { v[i + 1] = v[i] + arr[i]; } map<int, int> mp; int begin = 0, end = 0, answer = 0; mp[0] = 1; while (begin < n) { while (end < n && mp.find(v[end + 1]) == mp.end()) { end++; mp[v[end]] = 1; } // Check if another same element found // this means a subarray exist between // end and begin whose sum // of elements is equal to 0 answer = answer + end - begin; // Erase beginning element from map mp.erase(v[begin]); // Increase begin begin++; } // Print the result cout << answer << endl; } // Driver Code int main() { int arr[] = { 2, 4, -6 }; int size = sizeof(arr) / sizeof(arr[0]); numberOfSubarrays(arr, size); return 0; }
Java
// Java program to Count the no of subarray // which do not contain any subarray // whose sum of elements is equal to zero import java.util.*; class GFG{ // Function that print the number of // subarrays which do not contain any subarray // whose elements sum is equal to 0 static void numberOfSubarrays(int arr[], int n) { int []v = new int[n + 1]; v[0] = 0; // Storing each element as sum // of its previous element for (int i = 0; i < n; i++) { v[i + 1] = v[i] + arr[i]; } HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>(); int begin = 0, end = 0, answer = 0; mp.put(0, 1); while (begin < n) { while (end < n && !mp.containsKey(v[end + 1])) { end++; mp.put(v[end], 1); } // Check if another same element found // this means a subarray exist between // end and begin whose sum // of elements is equal to 0 answer = answer + end - begin; // Erase beginning element from map mp.remove(v[begin]); // Increase begin begin++; } // Print the result System.out.print(answer +"\n"); } // Driver Code public static void main(String[] args) { int arr[] = { 2, 4, -6 }; int size = arr.length; numberOfSubarrays(arr, size); } } // This code is contributed by sapnasingh4991
Python3
# Python 3 program to Count the no of subarray # which do not contain any subarray # whose sum of elements is equal to zero # Function that print the number of # subarrays which do not contain any subarray # whose elements sum is equal to 0 def numberOfSubarrays(arr, n): v = [0]*(n + 1) # Storing each element as sum # of its previous element for i in range( n): v[i + 1] = v[i] + arr[i] mp = {} begin, end, answer = 0 , 0 , 0 mp[0] = 1 while (begin < n): while (end < n and (v[end + 1]) not in mp): end += 1 mp[v[end]] = 1 # Check if another same element found # this means a subarray exist between # end and begin whose sum # of elements is equal to 0 answer = answer + end - begin # Erase beginning element from map del mp[v[begin]] # Increase begin begin += 1 # Print the result print(answer) # Driver Code if __name__ == "__main__": arr = [ 2, 4, -6 ] size = len(arr) numberOfSubarrays(arr, size) # This code is contributed by chitranayal
C#
// C# program to Count the no of subarray // which do not contain any subarray // whose sum of elements is equal to zero using System; using System.Collections.Generic; class GFG{ // Function that print the number of // subarrays which do not contain any subarray // whose elements sum is equal to 0 static void numberOfSubarrays(int []arr, int n) { int []v = new int[n + 1]; v[0] = 0; // Storing each element as sum // of its previous element for (int i = 0; i < n; i++) { v[i + 1] = v[i] + arr[i]; } Dictionary<int,int> mp = new Dictionary<int,int>(); int begin = 0, end = 0, answer = 0; mp.Add(0, 1); while (begin < n) { while (end < n && !mp.ContainsKey(v[end + 1])) { end++; mp.Add(v[end], 1); } // Check if another same element found // this means a subarray exist between // end and begin whose sum // of elements is equal to 0 answer = answer + end - begin; // Erase beginning element from map mp.Remove(v[begin]); // Increase begin begin++; } // Print the result Console.Write(answer +"\n"); } // Driver Code public static void Main(String[] args) { int []arr = { 2, 4, -6 }; int size = arr.Length; numberOfSubarrays(arr, size); } } // This code is contributed by Rajput-Ji
Javascript
<script> // JavaScript program to Count the no of subarray // which do not contain any subarray // whose sum of elements is equal to zero // Function that print the number of // subarrays which do not contain any subarray // whose elements sum is equal to 0 function numberOfSubarrays(arr, n) { let v = new Array(n + 1); v[0] = 0; // Storing each element as sum // of its previous element for (let i = 0; i < n; i++) { v[i + 1] = v[i] + arr[i]; } let mp = new Map(); let begin = 0, end = 0, answer = 0; mp.set(0, 1); while (begin < n) { while (end < n && !mp.has(v[end + 1])) { end++; mp.set(v[end], 1); } // Check if another same element found // this means a subarray exist between // end and begin whose sum // of elements is equal to 0 answer = answer + end - begin; // Erase beginning element from map mp.clear(); // Increase begin begin++; } // Print the result document.write(answer + "<br>"); } // Driver Code let arr = [ 2, 4, -6 ]; let size = arr.length; numberOfSubarrays(arr, size); // This code is contributed by _saurabh_jaiswal </script>
Producción:
5
Complejidad de tiempo: O(N)
Espacio Auxiliar: O(N)
Publicación traducida automáticamente
Artículo escrito por nitinkr8991 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA