Make the Array sum 0 by using either ceil or floor on each element | Python 3 program for the above approach ; Function to modify the array element such that the sum is close to 0 ; Stores the modified elements ; Stores the sum of array element ; Stores minimum size of the array ; Traverse the array and find the sum ; If sum is positive ; Find the minimum number of elements that must be changed ; Iterate until M elements are modified or the array end ; Update the current array elements to its floor ; Print the resultant array ; Driver Code
import sys NEW_LINE from math import ceil , floor NEW_LINE def setSumtoZero ( arr , N ) : NEW_LINE INDENT A = [ 0 for i in range ( N ) ] NEW_LINE sum = 0 NEW_LINE m = - sys . maxsize - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT sum += ceil ( arr [ i ] ) NEW_LINE A [ i ] = ceil ( arr [ i ] ) NEW_LINE DEDENT if ( sum > 0 ) : NEW_LINE INDENT m = min ( sum , N ) NEW_LINE i = 0 NEW_LINE while ( i < N and m > 0 ) : NEW_LINE INDENT A [ i ] = floor ( arr [ i ] ) NEW_LINE if ( A [ i ] != floor ( arr [ i ] ) ) : NEW_LINE INDENT m -= 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT print ( A [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ - 2 , - 2 , 4.5 ] NEW_LINE N = len ( arr ) NEW_LINE setSumtoZero ( arr , N ) NEW_LINE DEDENT