Minimize cost required to make all array elements greater than or equal to zero | Python3 program for the above approach ; Function to find the minimum cost to make all array of elements greater than or equal to 0 ; sort the array in ascending order ; stores the count 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 ; return minimum cost ; Given array ; size of the array ; Given value of x ; Function call to find minimum cost to make all array elements >= 0
import sys NEW_LINE def mincost ( arr , N , X ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE sum = 0 NEW_LINE cost = 0 NEW_LINE min_cost = sys . maxsize NEW_LINE for i in range ( 0 , N ) : NEW_LINE INDENT if ( arr [ i ] < 0 ) : NEW_LINE INDENT cost = abs ( arr [ i ] ) * x + ( sum - abs ( arr [ i ] ) * i ) NEW_LINE sum += abs ( arr [ i ] ) NEW_LINE min_cost = min ( min_cost , cost ) NEW_LINE DEDENT DEDENT return min_cost NEW_LINE DEDENT arr = [ - 1 , - 3 , - 2 , 4 , - 1 ] NEW_LINE N = len ( arr ) NEW_LINE x = 2 NEW_LINE print ( mincost ( arr , N , x ) ) NEW_LINE