Minimize cost required to make all array elements greater than or equal to zero | C ++ program for the above approach ; Function to find the minimum cost to make all array elements greater than or equal to 0 ; Sort the array in ascending order ; Stores the cost to make current array element >= 0 ; Stores the cost to make all array elements >= 0 ; Traverse the array and insert all the elements which are < 0 ; If current array element is negative ; Cost to make all array elements >= 0 ; Update curr if ans is minimum ; Print the minimum cost ; Driver Code ; Given array ; Size of the array ; Given value of X ; Function call to find minimum cost to make all array elements >= 0
#include <bits/stdc++.h> NEW_LINE using namespace std ; void minCost ( int arr [ ] , int N , int X ) { sort ( arr , arr + N ) ; int sum = 0 ; int cost = 0 ; int min_cost = INT_MAX ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] < 0 ) { cost = abs ( arr [ i ] ) * X + ( sum - abs ( arr [ i ] ) * i ) ; sum += abs ( arr [ i ] ) ; min_cost = min ( min_cost , cost ) ; } } cout << min_cost ; } int main ( ) { int arr [ ] = { -1 , -3 , -2 , 4 , -1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int X = 2 ; minCost ( arr , N , X ) ; return 0 ; }