Dada una array arr[] de N enteros positivos, la tarea es encontrar el costo mínimo para ordenar la array dada moviendo un elemento de la array a cualquier posición tal que el costo de mover ese elemento sea el valor de ese elemento.
Ejemplos:
Entrada: arr[] = {7, 1, 2, 3}
Salida: 6
Explicación:
Los siguientes son el conjunto de movimientos posibles para ordenar la array con un costo mínimo:
- Mover 1 al frente, arr[] = {1, 7, 2, 3}. costo = 1
- Mover 2 al segundo lugar, arr[] = {1, 2, 7, 3}. costo = 2
- Mover 3 al 3er lugar, arr[] = {1, 2, 3, 7}, costo = 3
Por lo tanto, el costo total es (1 + 2 + 3) = 6.
Entrada: arr[] = {7, 1, 2, 5}
Salida: 7
Enfoque: El problema dado se puede resolver usando Programación Dinámica . La idea es fijar los elementos de la array que forman la subsecuencia no decreciente más larga que tiene la suma máxima y realizar los movimientos dados para todos los elementos de la array restantes. Siga los pasos a continuación para resolver el problema:
- Encuentre la subsecuencia no decreciente más larga con la suma máxima y guárdela en una variable, digamos S .
- Después del paso anterior, imprima el valor de ( suma del elemento del arreglo – S) como el costo mínimo posible resultante de clasificar el arreglo dado .
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 sum of // non-decreasing subsequence int maxSumIS(int arr[], int n) { int i, j, max = 0; // Stores the maximum sum of subsequence ending at index i int dp[n]; // Initialize dp[] values for all indexes for (i = 0; i < n; i++) dp[i] = arr[i]; // Compute maximum sum values in bottom up manner for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] >= arr[j] && dp[i] < dp[j] + arr[i]) dp[i] = dp[j] + arr[i]; // Pick maximum of all msis values for (i = 0; i < n; i++) if (max < dp[i]) max = dp[i]; // Return the maximum sum as max return max; } // Function to find the minimum cost to // sort given array in increasing order int minCostSort(int arr[], int N) { // Find the sum of array int sm = 0; for (int i = 0; i < N; i++) sm += arr[i]; // Find the maximum sum non-decreasing subsequence int res = maxSumIS(arr, N); // Return the minimum cost return sm - res; } // Driver Code int main() { int arr[] = { 7, 1, 2, 3 }; int N = sizeof(arr) / sizeof(arr[0]); cout << minCostSort(arr, N); return 0; } // This code is contributed by Sania Kumari Gupta
C
// C program for the above approach #include <stdio.h> // Function to find the maximum sum of non-decreasing // subsequence int maxSumIS(int arr[], int n) { int i, j, max = 0; // Stores the maximum sum of subsequence ending at index i int dp[n]; // Initialize dp[] values for all indexes for (i = 0; i < n; i++) dp[i] = arr[i]; // Compute maximum sum values in bottom up manner for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] >= arr[j] && dp[i] < dp[j] + arr[i]) dp[i] = dp[j] + arr[i]; // Pick maximum of all msis values for (i = 0; i < n; i++) if (max < dp[i]) max = dp[i]; // Return the maximum sum as max return max; } // Function to find the minimum cost to // sort given array in increasing order int minCostSort(int arr[], int N) { // Find the sum of array int sm = 0; for (int i = 0; i < N; i++) sm += arr[i]; // Find the maximum sum non-decreasing subsequence int res = maxSumIS(arr, N); // Return the minimum cost return sm - res; } // Driver Code int main() { int arr[] = { 7, 1, 2, 3 }; int N = sizeof(arr) / sizeof(arr[0]); printf("%d", minCostSort(arr, N)); return 0; } // This code is contributed by Sania Kumari Gupta
Java
// Java program for the above approach import java.io.*; class GFG { // Function to find the maximum sum of // non-decreasing subsequence static int maxSumIS(int[] arr, int n) { int i, j, max = 0; // Stores the maximum sum of // subsequence ending at index i int[] dp = new int[n]; // Initialize dp[] values for all // indexes for (i = 0; i < n; i++) dp[i] = arr[i]; // Compute maximum sum values // in bottom up manner for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] >= arr[j] && dp[i] < dp[j] + arr[i]) dp[i] = dp[j] + arr[i]; // Pick maximum of all msis values for (i = 0; i < n; i++) { if (max < dp[i]) { max = dp[i]; } } // Return the maximum sum as max return max; } // Function to find the minimum cost to // sort given array in increasing order static int minCostSort(int[] arr, int N) { // Find the sum of array int sm = 0; for (int i = 0; i < N; i++) { sm += arr[i]; } // Find the maximum sum non-decreasing // subsequence int res = maxSumIS(arr, N); // Return the minimum cost return sm - res; } // Driver Code public static void main(String []args) { int[] arr = { 7, 1, 2, 3 }; int N = arr.length; System.out.print(minCostSort(arr, N)); } } // This code is contributed by shivanisinghss2110
Python3
# python program for the above approach # Function to find the maximum sum of # non-decreasing subsequence def maxSumIS(arr, n): max = 0 # Stores the maximum sum of # subsequence ending at index i dp = [0 for _ in range(n)] # Initialize dp[] values for all # indexes for i in range(0, n): dp[i] = arr[i] # Compute maximum sum values # in bottom up manner for i in range(1, n): for j in range(0, i): if (arr[i] >= arr[j] and dp[i] < dp[j] + arr[i]): dp[i] = dp[j] + arr[i] # Pick maximum of all msis values for i in range(0, n): if (max < dp[i]): max = dp[i] # Return the maximum sum as max return max # Function to find the minimum cost to # sort given array in increasing order def minCostSort(arr, N): # Find the sum of array sm = 0 for i in range(0, N): sm += arr[i] # Find the maximum sum non-decreasing # subsequence res = maxSumIS(arr, N) # Return the minimum cost return sm - res # Driver Code if __name__ == "__main__": arr = [7, 1, 2, 3] N = len(arr) print(minCostSort(arr, N)) # This code is contributed by rakeshsahni
C#
// C# program for the above approach using System; class GFG { // Function to find the maximum sum of // non-decreasing subsequence static int maxSumIS(int[] arr, int n) { int i, j, max = 0; // Stores the maximum sum of // subsequence ending at index i int[] dp = new int[n]; // Initialize dp[] values for all // indexes for (i = 0; i < n; i++) dp[i] = arr[i]; // Compute maximum sum values // in bottom up manner for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] >= arr[j] && dp[i] < dp[j] + arr[i]) dp[i] = dp[j] + arr[i]; // Pick maximum of all msis values for (i = 0; i < n; i++) { if (max < dp[i]) { max = dp[i]; } } // Return the maximum sum as max return max; } // Function to find the minimum cost to // sort given array in increasing order static int minCostSort(int[] arr, int N) { // Find the sum of array int sm = 0; for (int i = 0; i < N; i++) { sm += arr[i]; } // Find the maximum sum non-decreasing // subsequence int res = maxSumIS(arr, N); // Return the minimum cost return sm - res; } // Driver Code public static void Main() { int[] arr = { 7, 1, 2, 3 }; int N = arr.Length; Console.WriteLine(minCostSort(arr, N)); } } // This code is contributed by ukasp.
Javascript
<script> // JavaScript Program to implement // the above approach // Function to find the maximum sum of // non-decreasing subsequence function maxSumIS(arr, n) { let i, j, max = 0; // Stores the maximum sum of // subsequence ending at index i let dp = new Array(n); // Initialize dp[] values for all // indexes for (i = 0; i < n; i++) dp[i] = arr[i]; // Compute maximum sum values // in bottom up manner for (i = 1; i < n; i++) for (j = 0; j < i; j++) if (arr[i] >= arr[j] && dp[i] < dp[j] + arr[i]) dp[i] = dp[j] + arr[i]; // Pick maximum of all msis values for (i = 0; i < n; i++) { if (max < dp[i]) { max = dp[i]; } } // Return the maximum sum as max return max; } // Function to find the minimum cost to // sort given array in increasing order function minCostSort(arr, N) { // Find the sum of array let sm = 0; for (let i = 0; i < N; i++) { sm += arr[i]; } // Find the maximum sum non-decreasing // subsequence let res = maxSumIS(arr, N); // Return the minimum cost return sm - res; } // Driver Code let arr = [7, 1, 2, 3]; let N = arr.length; document.write(minCostSort(arr, N)); // This code is contributed by Potta Lokesh </script>
6
Tiempo Complejidad: O(N 2 )
Espacio Auxiliar: O(N)
Publicación traducida automáticamente
Artículo escrito por kartikmodi y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA