Make the Array sum 0 by using either ceil or floor on each element | 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
function setSumtoZero ( arr , N ) { let A = new Array ( N ) ; let sum = 0 ; let m = Number . MIN_VALUE ; for ( let i = 0 ; i < N ; i ++ ) { sum += Math . ceil ( arr [ i ] ) ; A [ i ] = Math . ceil ( arr [ i ] ) ; } if ( sum > 0 ) { m = Math . min ( sum , N ) ; for ( let i = 0 ; i < N && m > 0 ; i ++ ) { A [ i ] = Math . floor ( arr [ i ] ) ; if ( A [ i ] != Math . floor ( arr [ i ] ) ) m -- ; } } for ( let i = 0 ; i < N ; i ++ ) { document . write ( A [ i ] + " " ) ; } } let arr = [ - 2 , - 2 , 4.5 ] ; let N = arr . length ; setSumtoZero ( arr , N ) ;