Dada una array arr[] (indexación basada en 1) que consta de N enteros positivos y dos enteros positivos L y R , la tarea es encontrar la suma de los elementos de la array en el rango [L, R] si la array dada arr[] se está concatenando a sí misma infinitas veces.
Ejemplos:
Entrada: arr[] = {1, 2, 3}, L = 2, R = 8
Salida: 14
Explicación:
La array, arr[] después de la concatenación es {1, 2, 3, 1, 2, 3, 1, 2, …} y la suma de los elementos del índice 2 al 8 es 2 + 3 + 1 + 2 + 3 + 1 + 2 = 14.Entrada: arr[] = {5, 2, 6, 9}, L = 10, R = 13
Salida: 22
Enfoque ingenuo: el enfoque más simple para resolver el problema dado es iterar sobre el rango [L, R] usando la variable i y agregar el valor de arr[i % N] a la suma de cada índice. Después de completar la iteración, imprima el valor de la suma como la suma resultante.
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 sum of elements // in a given range of an infinite array void rangeSum(int arr[], int N, int L, int R) { // Stores the sum of array elements // from L to R int sum = 0; // Traverse from L to R for (int i = L - 1; i < R; i++) { sum += arr[i % N]; } // Print the resultant sum cout << sum; } // Driver Code int main() { int arr[] = { 5, 2, 6, 9 }; int L = 10, R = 13; int N = sizeof(arr) / sizeof(arr[0]); rangeSum(arr, N, L, R); return 0; }
Java
// Java program for the above approach import java.io.*; class GFG { // Function to find the sum of elements // in a given range of an infinite array static void rangeSum(int arr[], int N, int L, int R) { // Stores the sum of array elements // from L to R int sum = 0; // Traverse from L to R for (int i = L - 1; i < R; i++) { sum += arr[i % N]; } // Print the resultant sum System.out.println(sum); } // Driver Code public static void main(String[] args) { int arr[] = { 5, 2, 6, 9 }; int L = 10, R = 13; int N = arr.length; rangeSum(arr, N, L, R); } } // This code is contributed by Potta Lokesh
Python3
# Python 3 program for the above approach # Function to find the sum of elements # in a given range of an infinite array def rangeSum(arr, N, L, R): # Stores the sum of array elements # from L to R sum = 0 # Traverse from L to R for i in range(L - 1,R,1): sum += arr[i % N] # Print the resultant sum print(sum) # Driver Code if __name__ == '__main__': arr = [5, 2, 6, 9 ] L = 10 R = 13 N = len(arr) rangeSum(arr, N, L, R) # This code is contributed by divyeshrabadiya07
C#
// C# program for the above approach using System; class GFG { // Function to find the sum of elements // in a given range of an infinite array static void rangeSum(int[] arr, int N, int L, int R) { // Stores the sum of array elements // from L to R int sum = 0; // Traverse from L to R for (int i = L - 1; i < R; i++) { sum += arr[i % N]; } // Print the resultant sum Console.Write(sum); } // Driver Code public static void Main(string[] args) { int[] arr = { 5, 2, 6, 9 }; int L = 10, R = 13; int N = arr.Length; rangeSum(arr, N, L, R); } } // This code is contributed by ukasp.
Javascript
<script> // Javascript program for the above approach // Function to find the sum of elements // in a given range of an infinite array function rangeSum(arr, N, L, R) { // Stores the sum of array elements // from L to R let sum = 0; // Traverse from L to R for(let i = L - 1; i < R; i++) { sum += arr[i % N]; } // Print the resultant sum document.write(sum); } // Driver Code let arr = [ 5, 2, 6, 9 ]; let L = 10, R = 13; let N = arr.length rangeSum(arr, N, L, R); // This code is contributed by _saurabh_jaiswal </script>
22
Complejidad temporal: O(R – L)
Espacio auxiliar: O(1)
Enfoque eficiente: el enfoque anterior también se puede optimizar mediante el uso de Prefix Sum . Siga los pasos a continuación para resolver el problema:
- Inicialice una array , diga prefix[] de tamaño (N + 1) con todos los elementos como 0s .
- Recorra la array , arr[] usando la variable i y actualice prefix[i] a la suma de prefix[i – 1] y arr[i – 1] .
- Ahora, la suma de elementos sobre el rango [L, R] viene dada por:
la suma de elementos en el rango [1, R] – suma de elementos en el rango [1, L – 1] .
- Inicialice una variable, diga leftSum como ((L – 1)/N)*prefix[N] + prefix[(L – 1)%N] para almacenar la suma de elementos en el rango [1, L-1] .
- De manera similar, inicialice otra variable rightSum como (R/N)*prefix[N] + prefix[R%N] para almacenar la suma de elementos en el rango [1, R] .
- Después de completar los pasos anteriores, imprima el valor de (rightSum – leftSum) como la suma resultante de elementos en el rango dado [L, R] .
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 sum of elements // in a given range of an infinite array void rangeSum(int arr[], int N, int L, int R) { // Stores the prefix sum int prefix[N + 1]; prefix[0] = 0; // Calculate the prefix sum for (int i = 1; i <= N; i++) { prefix[i] = prefix[i - 1] + arr[i - 1]; } // Stores the sum of elements // from 1 to L-1 int leftsum = ((L - 1) / N) * prefix[N] + prefix[(L - 1) % N]; // Stores the sum of elements // from 1 to R int rightsum = (R / N) * prefix[N] + prefix[R % N]; // Print the resultant sum cout << rightsum - leftsum; } // Driver Code int main() { int arr[] = { 5, 2, 6, 9 }; int L = 10, R = 13; int N = sizeof(arr) / sizeof(arr[0]); rangeSum(arr, N, L, R); return 0; }
Java
// Java program for the above approach import java.io.*; class GFG{ // Function to find the sum of elements // in a given range of an infinite array static void rangeSum(int arr[], int N, int L, int R) { // Stores the prefix sum int prefix[] = new int[N+1]; prefix[0] = 0; // Calculate the prefix sum for (int i = 1; i <= N; i++) { prefix[i] = prefix[i - 1] + arr[i - 1]; } // Stores the sum of elements // from 1 to L-1 int leftsum = ((L - 1) / N) * prefix[N] + prefix[(L - 1) % N]; // Stores the sum of elements // from 1 to R int rightsum = (R / N) * prefix[N] + prefix[R % N]; // Print the resultant sum System.out.print( rightsum - leftsum); } // Driver Code public static void main (String[] args) { int arr[] = { 5, 2, 6, 9 }; int L = 10, R = 13; int N = arr.length; rangeSum(arr, N, L, R); } } // This code is contributed by shivanisinghss2110
Python3
# Python 3 program for the above approach # Function to find the sum of elements # in a given range of an infinite array def rangeSum(arr, N, L, R): # Stores the prefix sum prefix = [0 for i in range(N + 1)] prefix[0] = 0 # Calculate the prefix sum for i in range(1,N+1,1): prefix[i] = prefix[i - 1] + arr[i - 1] # Stores the sum of elements # from 1 to L-1 leftsum = ((L - 1) // N) * prefix[N] + prefix[(L - 1) % N] # Stores the sum of elements # from 1 to R rightsum = (R // N) * prefix[N] + prefix[R % N] # Print the resultant sum print(rightsum - leftsum) # Driver Code if __name__ == '__main__': arr = [5, 2, 6, 9] L = 10 R = 13 N = len(arr) rangeSum(arr, N, L, R) # This code is contributed by SURENDRA_GANGWAR.
C#
// C# program for the above approach using System; class GFG{ // Function to find the sum of elements // in a given range of an infinite array static void rangeSum(int []arr, int N, int L, int R) { // Stores the prefix sum int []prefix = new int[N+1]; prefix[0] = 0; // Calculate the prefix sum for (int i = 1; i <= N; i++) { prefix[i] = prefix[i - 1] + arr[i - 1]; } // Stores the sum of elements // from 1 to L-1 int leftsum = ((L - 1) / N) * prefix[N] + prefix[(L - 1) % N]; // Stores the sum of elements // from 1 to R int rightsum = (R / N) * prefix[N] + prefix[R % N]; // Print the resultant sum Console.Write( rightsum - leftsum); } // Driver Code public static void Main (String[] args) { int []arr = { 5, 2, 6, 9 }; int L = 10, R = 13; int N = arr.Length; rangeSum(arr, N, L, R); } } // This code is contributed by shivanisinghss2110
Javascript
<script> // JavaScript program for the above approach // Function to find the sum of elements // in a given range of an infinite array function rangeSum(arr, N, L, R) { // Stores the prefix sum let prefix = new Array(N + 1); prefix[0] = 0; // Calculate the prefix sum for (let i = 1; i <= N; i++) { prefix[i] = prefix[i - 1] + arr[i - 1]; } // Stores the sum of elements // from 1 to L-1 let leftsum = ((L - 1) / N) * prefix[N] + prefix[(L - 1) % N]; // Stores the sum of elements // from 1 to R let rightsum = (R / N) * prefix[N] + prefix[R % N]; // Print the resultant sum document.write(rightsum - leftsum); } // Driver Code let arr = [5, 2, 6, 9]; let L = 10, R = 13; let N = arr.length; rangeSum(arr, N, L, R); </script>
22
Complejidad temporal: O(N)
Espacio auxiliar: O(N)
Publicación traducida automáticamente
Artículo escrito por taoist_lee y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA