Minimize cost required to make all array elements greater than or equal to zero | Java 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
import java . util . Arrays ; public class GFG { static void minCost ( int arr [ ] , int N , int X ) { Arrays . sort ( arr ) ; int sum = 0 ; int cost = 0 ; int INT_MAX = Integer . MAX_VALUE ; int min_cost = INT_MAX ; 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 ) ; } } System . out . print ( min_cost ) ; } public static void main ( String [ ] args ) { int arr [ ] = { - 1 , - 3 , - 2 , 4 , - 1 } ; int N = arr . length ; int X = 2 ; minCost ( arr , N , X ) ; } }