Make the Array sum 0 by using either ceil or floor on each element | Java 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 java . util . * ; class GFG { static void setSumtoZero ( double arr [ ] , int N ) { int [ ] A = new int [ N ] ; int sum = 0 ; int m = Integer . MIN_VALUE ; for ( int i = 0 ; i < N ; i ++ ) { sum += Math . ceil ( arr [ i ] ) ; A [ i ] = ( int ) Math . ceil ( arr [ i ] ) ; } if ( sum > 0 ) { m = Math . min ( sum , N ) ; for ( int i = 0 ; i < N && m > 0 ; i ++ ) { A [ i ] = ( int ) Math . floor ( arr [ i ] ) ; if ( A [ i ] != Math . floor ( arr [ i ] ) ) m -- ; } } for ( int i = 0 ; i < N ; i ++ ) { System . out . print ( A [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { double arr [ ] = { - 2 , - 2 , 4.5 } ; int N = arr . length ; setSumtoZero ( arr , N ) ; } }