Dada una array arr[] de N elementos y Q consultas de la forma [X] . Para cada consulta, la tarea es encontrar el intervalo más grande [L, R] de la array tal que el elemento más grande en el intervalo sea arr[X] , tal que 1 ≤ L ≤ X ≤ R .
Nota: La array tiene una indexación basada en 1.
Ejemplos:
Entrada: N = 5, arr[] = {2, 1, 2, 3, 2}, Q = 3, query[] = {1, 2, 4} Salida: [1, 3] [2
,
2
]
[ 1, 5]
Explicación:
en la primera consulta, x = 1, entonces arr[x] = 2 y la respuesta es L = 1 y R = 3. aquí, podemos ver que max(arr[1], arr[2], arr[3]) = arr[x], que son los intervalos máximos.
En la segunda consulta, x = 2, entonces arr[x] = 1 y dado que es el elemento más pequeño de la array, el intervalo contiene solo un elemento, por lo que el rango es [2, 2].
En la tercera consulta, x = 4, por lo que arr[x] = 4, que es el elemento máximo de arr[], por lo que la respuesta es una array completa, L = 1 y R = N.Entrada: N = 4, arr[] = { 1, 2, 2, 4}, Q = 2, query[] = {1, 2} Salida: [1, 1] [1, 3] Explicación
:
En
la
primera
consulta , x = 1, entonces arr[x] = 1 y dado que es el elemento más pequeño de la array, el intervalo contiene solo un elemento, por lo que el rango es [1, 1].
En la segunda consulta, x = 2, entonces arr[x] = 2 y la respuesta es L = 1 y R = 3. aquí, podemos ver que max(arr[1], arr[2], arr[3]) = arr[x] = arr[2] = 2, que son los intervalos máximos.
Enfoque: la idea es precalcular el intervalo más grande para cada valor K en arr[] de 1 a N . A continuación se muestran los pasos:
- Para cada elemento K en arr[] , fije el índice del elemento K , luego encuentre cuánto podemos extender el intervalo hacia la izquierda y hacia la derecha.
- Disminuya el iterador izquierdo hasta que arr[left] ≤ K y, de manera similar, incremente el iterador derecho hasta que arr[right] ≤ K .
- El valor final de izquierda y derecha representa el índice inicial y final del intervalo, que se almacena en arrL[] y arrR[] respectivamente.
- Después de haber calculado previamente el rango de intervalo para cada valor. Luego, para cada consulta, necesitamos imprimir el rango de intervalo para arr[x] , es decir, arrL[arr[x]] y arrR[arr[x]] .
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 precompute the interval // for each query void utilLargestInterval(int arr[], int arrL[], int arrR[], int N) { // For every values [1, N] find // the longest intervals for (int maxValue = 1; maxValue <= N; maxValue++) { int lastIndex = 0; // Iterate the array arr[] for (int i = 1; i <= N; i++) { if (lastIndex >= i || arr[i] != maxValue) continue; int left = i, right = i; // Shift the left pointers while (left > 0 && arr[left] <= maxValue) left--; // Shift the right pointers while (right <= N && arr[right] <= maxValue) right++; left++, right--; lastIndex = right; // Store the range of interval // in arrL[] and arrR[]. for (int j = left; j <= right; j++) { if (arr[j] == maxValue) { arrL[j] = left; arrR[j] = right; } } } } } // Function to find the largest interval // for each query in Q[] void largestInterval( int arr[], int query[], int N, int Q) { // To store the L and R of X int arrL[N + 1], arrR[N + 1]; // Function Call utilLargestInterval(arr, arrL, arrR, N); // Iterate to find ranges for each query for (int i = 0; i < Q; i++) { cout << "[" << arrL[query[i]] << ", " << arrR[query[i]] << "]\n"; } } // Driver Code int main() { int N = 5, Q = 3; // Given array arr[] int arr[N + 1] = { 0, 2, 1, 2, 3, 2 }; // Given Queries int query[Q] = { 1, 2, 4 }; // Function Call largestInterval(arr, query, N, Q); return 0; }
Java
// Java program for the above approach class GFG{ // Function to precompute the interval // for each query static void utilLargestInterval(int arr[], int arrL[], int arrR[], int N) { // For every values [1, N] find // the longest intervals for(int maxValue = 1; maxValue <= N; maxValue++) { int lastIndex = 0; // Iterate the array arr[] for(int i = 1; i <= N; i++) { if (lastIndex >= i || arr[i] != maxValue) continue; int left = i, right = i; // Shift the left pointers while (left > 0 && arr[left] <= maxValue) left--; // Shift the right pointers while (right <= N && arr[right] <= maxValue) right++; left++; right--; lastIndex = right; // Store the range of interval // in arrL[] and arrR[]. for(int j = left; j <= right; j++) { if (arr[j] == maxValue) { arrL[j] = left; arrR[j] = right; } } } } } // Function to find the largest interval // for each query in Q[] static void largestInterval(int arr[], int query[], int N, int Q) { // To store the L and R of X int []arrL = new int[N + 1]; int []arrR = new int[N + 1]; // Function Call utilLargestInterval(arr, arrL, arrR, N); // Iterate to find ranges for // each query for(int i = 0; i < Q; i++) { System.out.print("[" + arrL[query[i]] + ", " + arrR[query[i]] + "]\n"); } } // Driver Code public static void main(String[] args) { int N = 5, Q = 3; // Given array arr[] int arr[] = { 0, 2, 1, 2, 3, 2 }; // Given queries int query[] = { 1, 2, 4 }; // Function call largestInterval(arr, query, N, Q); } } // This code is contributed by Amit Katiyar
Python3
# Python3 program for the above approach # Function to precompute the interval # for each query def utilLargestInterval(arr, arrL, arrR, N): # For every values [1, N] find # the longest intervals for maxValue in range(1, N + 1): lastIndex = 0 # Iterate the array arr[] for i in range(N + 1): if (lastIndex >= i or arr[i] != maxValue): continue left = i right = i # Shift the left pointers while (left > 0 and arr[left] <= maxValue): left -= 1 # Shift the right pointers while (right <= N and arr[right] <= maxValue): right += 1 left += 1 right -= 1 lastIndex = right # Store the range of interval # in arrL[] and arrR[]. for j in range(left, right + 1): if (arr[j] == maxValue): arrL[j] = left arrR[j] = right # Function to find the largest interval # for each query in Q[] def largestInterval(arr, query, N, Q): # To store the L and R of X arrL = [0 for i in range(N + 1)] arrR = [0 for i in range(N + 1)] # Function call utilLargestInterval(arr, arrL, arrR, N); # Iterate to find ranges for each query for i in range(Q): print('[' + str(arrL[query[i]]) + ', ' + str(arrR[query[i]]) + ']') # Driver code if __name__=="__main__": N = 5 Q = 3 # Given array arr[] arr = [ 0, 2, 1, 2, 3, 2 ] # Given Queries query = [ 1, 2, 4 ] # Function call largestInterval(arr, query, N, Q) # This code is contributed by rutvik_56
C#
// C# program for the above approach using System; class GFG{ // Function to precompute the interval // for each query static void utilLargestInterval(int []arr, int []arrL, int []arrR, int N) { // For every values [1, N] find // the longest intervals for(int maxValue = 1; maxValue <= N; maxValue++) { int lastIndex = 0; // Iterate the array []arr for(int i = 1; i <= N; i++) { if (lastIndex >= i || arr[i] != maxValue) continue; int left = i, right = i; // Shift the left pointers while (left > 0 && arr[left] <= maxValue) left--; // Shift the right pointers while (right <= N && arr[right] <= maxValue) right++; left++; right--; lastIndex = right; // Store the range of interval // in arrL[] and arrR[]. for(int j = left; j <= right; j++) { if (arr[j] == maxValue) { arrL[j] = left; arrR[j] = right; } } } } } // Function to find the largest interval // for each query in Q[] static void largestInterval(int []arr, int []query, int N, int Q) { // To store the L and R of X int []arrL = new int[N + 1]; int []arrR = new int[N + 1]; // Function Call utilLargestInterval(arr, arrL, arrR, N); // Iterate to find ranges for // each query for(int i = 0; i < Q; i++) { Console.Write("[" + arrL[query[i]] + ", " + arrR[query[i]] + "]\n"); } } // Driver Code public static void Main(String[] args) { int N = 5, Q = 3; // Given array []arr int []arr = { 0, 2, 1, 2, 3, 2 }; // Given queries int []query = { 1, 2, 4 }; // Function call largestInterval(arr, query, N, Q); } } // This code is contributed by Princi Singh
Javascript
<script> // Javascript program for the above approach // Function to precompute the interval // for each query function utilLargestInterval(arr, arrL, arrR, N) { // For every values [1, N] find // the longest intervals for (var maxValue = 1; maxValue <= N; maxValue++) { var lastIndex = 0; // Iterate the array arr[] for (var i = 1; i <= N; i++) { if (lastIndex >= i || arr[i] != maxValue) continue; var left = i, right = i; // Shift the left pointers while (left > 0 && arr[left] <= maxValue) left--; // Shift the right pointers while (right <= N && arr[right] <= maxValue) right++; left++, right--; lastIndex = right; // Store the range of interval // in arrL[] and arrR[]. for (var j = left; j <= right; j++) { if (arr[j] == maxValue) { arrL[j] = left; arrR[j] = right; } } } } } // Function to find the largest interval // for each query in Q[] function largestInterval( arr, query, N, Q) { // To store the L and R of X var arrL = Array(N+1).fill(0),arrR = Array(N+1).fill(0); // Function Call utilLargestInterval(arr, arrL, arrR, N); // Iterate to find ranges for each query for (var i = 0; i < Q; i++) { document.write( "[" + arrL[query[i]] + ", " + arrR[query[i]] + "]<br>"); } } // Driver Code var N = 5, Q = 3; // Given array arr[] var arr = [0, 2, 1, 2, 3, 2]; // Given Queries var query = [1, 2, 4]; // Function Call largestInterval(arr, query, N, Q); // This code is contributed by itsok. </script>
[1, 3] [2, 2] [1, 5]
Complejidad de Tiempo: O(Q + N 2 )
Espacio Auxiliar: O(N)
Publicación traducida automáticamente
Artículo escrito por grand_master y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA