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
using System ; class GFG { static void minCost ( int [ ] arr , int N , int X ) { Array . Sort ( arr ) ; int sum = 0 ; int cost = 0 ; int INT_MAX = Int32 . MaxValue ; int min_cost = Int32 . MaxValue ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] < 0 ) { cost = Math . Abs ( arr [ i ] ) * X + ( sum - Math . Abs ( arr [ i ] ) * i ) ; sum += Math . Abs ( arr [ i ] ) ; min_cost = Math . Min ( min_cost , cost ) ; } } Console . Write ( min_cost ) ; } static public void Main ( ) { int [ ] arr = { - 1 , - 3 , - 2 , 4 , - 1 } ; int N = arr . Length ; int X = 2 ; minCost ( arr , N , X ) ; } }