Make the Array sum 0 by using either ceil or floor on each element | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void setSumtoZero ( double arr [ ] , int N ) { int A [ N ] ; int sum = 0 ; int m = INT_MIN ; for ( int i = 0 ; i < N ; i ++ ) { sum += ceil ( arr [ i ] ) ; A [ i ] = ceil ( arr [ i ] ) ; } if ( sum > 0 ) { m = min ( sum , N ) ; for ( int i = 0 ; i < N && m > 0 ; i ++ ) { A [ i ] = floor ( arr [ i ] ) ; if ( A [ i ] != floor ( arr [ i ] ) ) m -- ; } } for ( int i = 0 ; i < N ; i ++ ) { cout << A [ i ] << " ▁ " ; } } int main ( ) { double arr [ ] = { -2 , -2 , 4.5 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; setSumtoZero ( arr , N ) ; return 0 ; }