Dada una array arr[] que consiste en N enteros y un entero X , la tarea es encontrar el costo mínimo requerido para hacer que todos los elementos de la array sean mayores o iguales a 0 realizando las siguientes operaciones cualquier cantidad de veces:
- Aumente cualquier elemento de la array en 1. Costo = 1.
- Aumente todos los elementos de la array en 1. Costo = X.
Ejemplos:
Entrada: arr[] = {-1, -3, 3, 4, 5}, X = 2
Salida: 4
Explicación:
Incremente arr[0] en 1. La array arr[] se modifica a {0, -3, 3 , 4, 5}. Costo = 1.
Incremente arr[1] en 1 tres veces. La array arr[] se modifica a {0, 0, 3, 4, 5}. Por lo tanto, Costo = 4.
Por lo tanto, el costo total requerido es 4.Entrada: arr[] = {-3, -2, -1, -5, 7}, X = 2
Salida: 8
Enfoque: la idea es utilizar el enfoque codicioso para resolver el problema. Siga los pasos a continuación para resolver el problema:
- Ordene la array arr[] en orden ascendente.
- Inicialice un vector auxiliar , digamos una lista, para almacenar los elementos negativos de la array.
- Inicialice una variable, cost = 0, para almacenar el costo requerido para hacer que el elemento de array actual sea 0 y otra variable, min_cost = INT_MAX , para almacenar el costo mínimo final para hacer que todos los elementos de array sean >= 0 .
- Recorra la array arr[] e intente convertir todos los elementos de la array en la lista >= 0 aplicando las operaciones adecuadas y actualice min_cost en consecuencia.
- Imprime el valor de min_cost como respuesta.
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 minimum // cost to make all array elements // greater than or equal to 0 void minCost(int arr[], int N, int X) { // Sort the array in // ascending order sort(arr, arr + N); int sum = 0; // Stores the cost to make // current array element >= 0 int cost = 0; // Stores the cost to make // all array elements >= 0 int min_cost = INT_MAX; // Traverse the array and insert all the // elements which are < 0 for (int i = 0; i < N; i++) { // If current array element // is negative if (arr[i] < 0) { // Cost to make all array // elements >= 0 cost = abs(arr[i]) * X + (sum - abs(arr[i]) * i); sum += abs(arr[i]); // Update curr if ans is minimum min_cost = min(min_cost, cost); } } // Print the minimum cost cout << min_cost; } // Driver Code int main() { // Given array int arr[] = { -1, -3, -2, 4, -1 }; // Size of the array int N = sizeof(arr) / sizeof(arr[0]); // Given value of X int X = 2; // Function call to find minimum // cost to make all array elements >= 0 minCost(arr, N, X); return 0; }
Java
// Java program for the above approach import java.util.Arrays; public class GFG { // Function to find the minimum // cost to make all array elements // greater than or equal to 0 static void minCost(int arr[], int N, int X) { // Sort the array in // ascending order Arrays.sort(arr) ; int sum = 0; // Stores the cost to make // current array element >= 0 int cost = 0; int INT_MAX = Integer.MAX_VALUE; // Stores the cost to make // all array elements >= 0 int min_cost = INT_MAX; // Traverse the array and insert all the // elements which are < 0 for (int i = 0; i < N; i++) { // If current array element // is negative if (arr[i] < 0) { // Cost to make all array // elements >= 0 cost = Math.abs(arr[i]) * X + (sum - Math.abs(arr[i]) * i); sum += Math.abs(arr[i]); // Update curr if ans is minimum min_cost = Math.min(min_cost, cost); } } // Print the minimum cost System.out.print(min_cost); } // Driver Code public static void main (String[] args) { // Given array int arr[] = { -1, -3, -2, 4, -1 }; // Size of the array int N = arr.length; // Given value of X int X = 2; // Function call to find minimum // cost to make all array elements >= 0 minCost(arr, N, X); } } // This code is contributed by AnkThon
Python3
# Python3 program for the above approach import sys # Function to find the minimum # cost to make all array of elements # greater than or equal to 0 def mincost(arr, N, X): # sort the array in # ascending order arr.sort() sum = 0 # stores the count to make # current array element >=0 cost = 0 # stores the cost to make # all array elements >=0 min_cost = sys.maxsize # Traverse the array and insert all the # elements which are <=0 for i in range(0, N): # if current array element # is negative if (arr[i] < 0): # cost to make all array # elements >=0 cost = abs(arr[i]) * x + (sum - abs(arr[i]) * i) sum += abs(arr[i]) # update curr if ans is minimum min_cost = min(min_cost,cost) # return minimum cost return min_cost # Driver code arr = [-1, -3, -2, 4, -1] # size of the array N = len(arr) # Given value of x x = 2 # Function call to find minimum # cost to make all array elements >=0 print(mincost(arr, N, x)) # This code is contributed by Virusbuddah
C#
// C# program for the above approach using System; class GFG{ // Function to find the minimum // cost to make all array elements // greater than or equal to 0 static void minCost(int[] arr, int N, int X) { // Sort the array in // ascending order Array.Sort(arr) ; int sum = 0; // Stores the cost to make // current array element >= 0 int cost = 0; //int INT_MAX = Int32.MaxValue; // Stores the cost to make // all array elements >= 0 int min_cost = Int32.MaxValue; // Traverse the array and insert all the // elements which are < 0 for(int i = 0; i < N; i++) { // If current array element // is negative if (arr[i] < 0) { // Cost to make all array // elements >= 0 cost = Math.Abs(arr[i]) * X + (sum - Math.Abs(arr[i]) * i); sum += Math.Abs(arr[i]); // Update curr if ans is minimum min_cost = Math.Min(min_cost, cost); } } // Print the minimum cost Console.Write(min_cost); } // Driver Code static public void Main () { // Given array int[] arr = { -1, -3, -2, 4, -1 }; // Size of the array int N = arr.Length; // Given value of X int X = 2; // Function call to find minimum // cost to make all array elements >= 0 minCost(arr, N, X); } } // This code is contributed by susmitakundugoaldanga
Javascript
<script> // javascript program for the above approach // Function to find the minimum // cost to make all array elements // greater than or equal to 0 function minCost(arr , N , X) { // Sort the array in // ascending order arr.sort() ; var sum = 0; // Stores the cost to make // current array element >= 0 var cost = 0; var INT_MAX = Number.MAX_VALUE; // Stores the cost to make // all array elements >= 0 var min_cost = INT_MAX; // Traverse the array and insert all the // elements which are < 0 for (i = 0; i < N; i++) { // If current array element // is negative if (arr[i] < 0) { // Cost to make all array // elements >= 0 cost = Math.abs(arr[i]) * X + (sum - Math.abs(arr[i]) * i); sum += Math.abs(arr[i]); // Update curr if ans is minimum min_cost = Math.min(min_cost, cost); } } // Print the minimum cost document.write(min_cost); } // Driver Code //Given array var arr = [ -1, -3, -2, 4, -1 ]; // Size of the array var N = arr.length; // Given value of X var X = 2; // Function call to find minimum // cost to make all array elements >= 0 minCost(arr, N, X); // This code is contributed by 29AjayKumar </script>
5
Complejidad de tiempo: O(N * logN)
Espacio auxiliar: O(1)
Publicación traducida automáticamente
Artículo escrito por hemanthswarna1506 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA