Dada una array arr[] de tamaño N, que consta de N/2 enteros pares e impares cada uno, y un entero K , la tarea es encontrar el resto máximo de la suma de un par de elementos de la array de diferente paridad módulo K.
Ejemplos:
Entrada: arr[] = {3, 2, 4, 11, 6, 7}, K = 7
Salida: 6
Explicación:
Suma de un par de elementos de array = 2 + 11
Suma % K = 13 % 7 = 6.
Por lo tanto , el resto máximo posible es 6.Entrada: arr[] = {8, 11, 17, 16}, K = 13
Salida: 12
Enfoque: siga los pasos a continuación para resolver el problema:
- Inicialice un HashSet , digamos even , para almacenar todos los elementos de array pares.
- Inicialice un TreeSet , digamos impar, para almacenar todos los elementos de array impares.
- Inicialice una variable, digamos max_rem, para almacenar el resto máximo posible.
- Recorra el HashSet y para cada elemento, encuentre su complemento y búsquelo en el conjunto impar , que es menor que igual a su complemento.
- Actualice max_rem con la suma de los elementos y su complemento.
- Imprime el resto máximo, es decir, el valor de max_rem .
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 the maximum // remainder of sum of a pair // of array elements modulo K void maxRemainder(int A[], int N, int K) { // Stores all even numbers unordered_set<int> even; // Stores all odd numbers set<int> odd; // Segregate remainders of even // and odd numbers in respective sets for(int i = 0; i < N; i++) { int num = A[i]; if (num % 2 == 0) even.insert(num % K); else odd.insert(num % K); } // Stores the maximum // remainder obtained int max_rem = 0; // Find the complement of remainder // of each even number in odd set for(int x : even) { // Find the complement // of remainder x int y = K - 1 - x; auto it = odd.upper_bound(y); if (it != odd.begin()) { it--; max_rem = max(max_rem, x + *it); } } // Print the answer cout << max_rem; } // Driver code int main() { // Given array int arr[] = { 3, 2, 4, 11, 6, 7 }; // Size of the array int N = sizeof(arr) / sizeof(arr[0]); // Given value of K int K = 7; maxRemainder(arr, N, K); return 0; } // This code is contributed by Kingash
Java
// Java program for the above approach import java.util.*; class GFG { // Function to find the maximum // remainder of sum of a pair // of array elements modulo K static void maxRemainder(int A[], int N, int K) { // Stores all even numbers HashSet<Integer> even = new HashSet<>(); // Stores all odd numbers TreeSet<Integer> odd = new TreeSet<>(); // Segregate remainders of even // and odd numbers in respective sets for (int num : A) { if (num % 2 == 0) even.add(num % K); else odd.add(num % K); } // Stores the maximum // remainder obtained int max_rem = 0; // Find the complement of remainder // of each even number in odd set for (int x : even) { // Find the complement // of remainder x int y = K - 1 - x; if (odd.floor(y) != null) max_rem = Math.max( max_rem, x + odd.floor(y)); } // Print the answer System.out.print(max_rem); } // Driver Code public static void main(String[] args) { // Given array int arr[] = { 3, 2, 4, 11, 6, 7 }; // Size of the array int N = arr.length; // Given value of K int K = 7; maxRemainder(arr, N, K); } }
Python3
# Python3 program for the above approach from bisect import bisect_left # Function to find the maximum # remainder of sum of a pair # of array elements modulo K def maxRemainder(A, N, K): # Stores all even numbers even = {} # Stores all odd numbers odd = {} # Segregate remainders of even # and odd numbers in respective sets for i in range(N): num = A[i] if (num % 2 == 0): even[num % K] = 1 else: odd[num % K] = 1 # Stores the maximum # remainder obtained max_rem = 0 # Find the complement of remainder # of each even number in odd set for x in even: # Find the complement # of remainder x y = K - 1 - x od = list(odd.keys()) it = bisect_left(od, y) if (it != 0): max_rem = max(max_rem, x + od[it]) # Print the answer print (max_rem) # Driver code if __name__ == '__main__': # Given array arr = [3, 2, 4, 11, 6, 7] # Size of the array N = len(arr) # Given value of K K = 7 maxRemainder(arr, N, K) # This code is contributed by mohit kumar 29
Javascript
// JavaScript program for the above approach // Function to find the upper bound of an array. function upper_bound(arr, X) { let mid; // Initialise starting index and // ending index let low = 0; let high = arr.length; // Till low is less than high while (low < high) { // Find the middle index mid = low + Math.floor((high - low) / 2); // If X is greater than or equal // to arr[mid] then find // in right subarray if (X >= arr[mid]) { low = mid + 1; } // If X is less than arr[mid] // then find in left subarray else { high = mid; } } // if X is greater than arr[n-1] if(low < N && arr[low] <= X) { low++; } // Return the upper_bound index return low; } // Function to find the maximum // remainder of sum of a pair // of array elements modulo K function maxRemainder(A, N, K) { // Stores all even numbers let even = new Array(); // Stores all odd numbers let odd = new Array(); // Segregate remainders of even // and odd numbers in respective sets for(let i = 0; i < N; i++) { let num = A[i]; if (num % 2 == 0 && !even.includes(num%K)){ even.push(num % K); } else if(num%2 != 0 && !odd.includes(num%K)){ odd.push(num % K); } } odd.sort(); // Stores the maximum // remainder obtained let max_rem = 0; // Find the complement of remainder // of each even number in odd set for(let i = 0;i < even.length; i++){ let x = even[i]; // Find the complement // of remainder xd // console.log(x); let y = K - 1 - x; let it = upper_bound(odd, y); if (it != 0) { it--; max_rem = Math.max(max_rem, x + odd[it]); } } // Print the answer console.log(max_rem); } // Driver code // Given array let arr = [3, 2, 4, 11, 6, 7]; // Size of the array let N = arr.length; // Given value of K let K = 7; maxRemainder(arr, N, K); // This code is contributed by Nidhi goel
6
Complejidad temporal: O(N * logN)
Espacio auxiliar: O(N)
Publicación traducida automáticamente
Artículo escrito por hemanthswarna1506 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA