Minimum operations required to make all elements in an array of first N odd numbers equal | Function to find the minimum number of operations required to make the array elements equal ; Stores the array elements ; Stores the sum of the array ; Iterate over the range [ 0 , N ] ; Update the value arr [ i ] ; Increment the sum by the value arr [ i ] ; Stores the middle element ; If N is even ; Otherwise ; Stores the result ; Traverse the range [ 0 , N / 2 ] ; Update the value of ans ; Return the result ; Driver Code
function minOperations ( N ) { let arr = Array . from ( { length : N } , ( _ , i ) => 0 ) ; let sum = 0 ; for ( let i = 0 ; i < N ; i ++ ) { arr [ i ] = ( 2 * i ) + 1 ; sum = sum + arr [ i ] ; } let mid = 0 ; if ( N % 2 == 0 ) { mid = sum / N ; } else { mid = arr [ N / 2 ] ; } let ans = 0 ; for ( let i = 0 ; i < N / 2 ; i ++ ) { ans += mid - arr [ i ] ; } return ans ; } let N = 6 ; document . write ( minOperations ( N ) ) ;