Minimize cost required to make all array elements greater than or equal to zero | 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 ; Prvar the minimum cost ; Given array ; Size of the array ; Given value of X ; Function call to find minimum cost to make all array elements >= 0
function minCost ( arr , N , X ) { arr . sort ( ) ; var sum = 0 ; var cost = 0 ; var INT_MAX = Number . MAX_VALUE ; var min_cost = INT_MAX ; for ( 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 ) ; } } document . write ( min_cost ) ; } var arr = [ - 1 , - 3 , - 2 , 4 , - 1 ] ; var N = arr . length ; var X = 2 ; minCost ( arr , N , X ) ;