Dada una array arr[] que consta de N enteros positivos y un entero K , la tarea es igualar la suma de todos los subarreglos de longitud K reemplazando el número mínimo de elementos de la array con cualquier entero.
Ejemplos:
Entrada: arr[] = {3, 4, 3, 5, 6}, K = 2
Salida: 2
Explicación:
Operación 1: Reemplazar arr[3] por 4 modifica arr[] a {3, 4, 3, 4, 6}.
Operación 2: Reemplazar arr[4] por 3 modifica arr[] a {3, 4, 3, 4, 3}.
Todos los subarreglos de longitud 2 son {{3, 4}, {4, 3}, {3, 4}, {4, 3}}. La suma de todos estos subarreglos es 7. Por lo tanto, el número mínimo de operaciones requeridas es 2.Entrada: arr[] = {1, 2, 3, 1, 2}, K = 3
Salida: 0
Explicación: Todos los subarreglos de longitud 3 son {{1, 2, 3}, {2, 3, 1}, { 3, 1, 2}}. Dado que todos estos subarreglos tienen una suma de 6, el número de operaciones requeridas es 0.
Enfoque: La idea se basa en la observación de que todos los subarreglos tendrán la misma suma, cuando todos los elementos separados por la distancia K sean iguales.
Por lo tanto, el problema se puede resolver contando la frecuencia de elementos separados por una distancia K y encontrar el número que aparece el máximo de veces. Siga los pasos a continuación para resolver el problema:
- Inicialice una variable y almacene el resultado requerido.
- Iterar en el rango [0, K-1] usando la variable i
- Cree un mapa , freq para almacenar la frecuencia de los elementos separados por una distancia K a partir de i .
- Recorre el mapa y encuentra el elemento que aparece el máximo número de veces.
- Nuevamente, recorra el mapa y si el elemento no es igual al elemento máximo que ocurre, agregue su frecuencia a ans .
- Imprime el valor de ans como resultado.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to find minimum number of // operations required to make sum of // all subarrays of size K equal void findMinOperations(int arr[], int N, int K) { // Stores number of operations int operations = 0; // Iterate in the range [0, K-1] for (int i = 0; i < K; i++) { // Stores frequency of elements // separated by distance K unordered_map<int, int> freq; for (int j = i; j < N; j += K) freq[arr[j]]++; // Stores maximum frequency // and corresponding element int max1 = 0, num; // Find max frequency element // and its frequency for (auto x : freq) { if (x.second > max1) { max1 = x.second; num = x.first; } } // Update the number of operations for (auto x : freq) { if (x.first != num) operations += x.second; } } // Print the result cout << operations; } // Driver Code int main() { // Given Input int arr[] = { 3, 4, 3, 5, 6 }; int K = 2; int N = sizeof(arr) / sizeof(arr[0]); // Function Call findMinOperations(arr, N, K); return 0; }
Java
// Java program for the above approach import java.lang.*; import java.util.*; class GFG { // Function to find minimum number of // operations required to make sum of // all subarrays of size K equal static void findMinOperations(int arr[], int N, int K) { // Stores number of operations int operations = 0; // Iterate in the range [0, K-1] for (int i = 0; i < K; i++) { // Stores frequency of elements // separated by distance K Map<Integer, Integer> freq=new HashMap<>(); for (int j = i; j < N; j += K) freq.put(arr[j], freq.getOrDefault(arr[j],0)+1); // Stores maximum frequency // and corresponding element int max1 = 0, num=-1; // Find max frequency element // and its frequency for (Map.Entry<Integer,Integer> x : freq.entrySet()) { if (x.getValue() > max1) { max1 = x.getValue(); num = x.getKey(); } } // Update the number of operations for ( Map.Entry<Integer,Integer> x : freq.entrySet()) { if (x.getKey() != num) operations += x.getValue(); } } // Print the result System.out.print(operations); } // Driver code public static void main(String[] args) { // Given Input int arr[] = { 3, 4, 3, 5, 6 }; int K = 2; int N = arr.length; // Function Call findMinOperations(arr, N, K); } } // This code is contributed by offbeat
Python3
# python 3 program for the above approach # Function to find minimum number of # operations required to make sum of # all subarrays of size K equal def findMinOperations(arr, N, K): # Stores number of operations operations = 0 # Iterate in the range [0, K-1] for i in range(K): # Stores frequency of elements # separated by distance K freq = {} for j in range(i,N,K): if arr[j] in freq: freq[arr[j]] += 1 else: freq[arr[j]] = 1 # Stores maximum frequency # and corresponding element max1 = 0 num = 0 # Find max frequency element # and its frequency for key,value in freq.items(): if (value > max1): max1 = value num = key # Update the number of operations for key,value in freq.items(): if (key != num): operations += value # Print the result print(operations) # Driver Code if __name__ == '__main__': # Given Input arr = [3, 4, 3, 5, 6] K = 2 N = len(arr) # Function Call findMinOperations(arr, N, K) # This code is contributed by ipg2016107.
C#
// C# program for the above approach using System; using System.Collections.Generic; class GFG{ // Function to find minimum number of // operations required to make sum of // all subarrays of size K equal static void findMinOperations(int []arr, int N, int K) { // Stores number of operations int operations = -1; // Iterate in the range [0, K-1] for(int i = 0; i < K; i++) { // Stores frequency of elements // separated by distance K Dictionary<int, int> freq = new Dictionary<int, int>(); for(int j = i; j < N; j += K) { if (freq.ContainsKey(arr[j])) freq[arr[j]]++; else freq.Add(arr[j], 1); } // Stores maximum frequency // and corresponding element int max1 = -1, num = 0; // Find max frequency element // and its frequency foreach(KeyValuePair<int, int> entry in freq) { if (entry.Key > max1) { max1 = entry.Value; num = entry.Key; } } // Update the number of operations foreach(KeyValuePair<int, int> entry in freq) { if (entry.Key != num) operations += entry.Value; } } // Print the result Console.Write(operations); } // Driver Code public static void Main() { // Given Input int []arr = { 3, 4, 3, 5, 6 }; int K = 2; int N = arr.Length; // Function Call findMinOperations(arr, N, K); } } // This code is contributed by SURENDRA_GANGWAR
Javascript
<script> // JavaScript program for the above approach // Function to find minimum number of // operations required to make sum of // all subarrays of size K equal function findMinOperations(arr, N, K) { // Stores number of operations var operations = 0; var i,j; // Iterate in the range [0, K-1] for (i = 0; i < K; i++) { // Stores frequency of elements // separated by distance K var freq = new Map(); for(j = i; j < N; j += K){ if(freq.has(arr[j])) freq.set(arr[j], freq.get(arr[j])+1); else freq.set(arr[j],1); } // Stores maximum frequency // and corresponding element var max1 = 0, num; // Find max frequency element // and its frequency for (const [key, value] of freq.entries()) { if (value > max1) { max1 = value; num = key; } } // Update the number of operations for (const [key, value] of freq.entries()) { if (key != num) operations += value; } } // Print the result document.write(operations); } // Driver Code // Given Input var arr = [3, 4, 3, 5, 6]; var K = 2; var N = arr.length; // Function Call findMinOperations(arr, N, K); </script>
2
Complejidad temporal: O(N)
Espacio auxiliar: O(N)
Publicación traducida automáticamente
Artículo escrito por pawanharwani11 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA