Minimum steps to make the product of the array equal to 1 | Function to return the minimum steps required ; To store the count of 0 s , positive and negative numbers ; To store the ans ; If array element is equal to 0 ; If array element is a negative number ; Extra cost needed to make it - 1 ; If array element is a positive number ; Extra cost needed to make it 1 ; Now the array will have - 1 , 0 and 1 only ; As count of negative is even so we will change all 0 to 1 total cost here will be count of 0 s ; If there are zeroes present in the array ; Change one zero to - 1 and rest of them to 1 Total cost here will be count of '0' ; If there are no zeros in the array ; As no 0 s are available so we have to change one - 1 to 1 which will cost 2 to change - 1 to 1 ; Driver code
function MinStep ( a , n ) { let positive = 0 , negative = 0 , zero = 0 ; let step = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( a [ i ] == 0 ) { zero ++ ; } else if ( a [ i ] < 0 ) { negative ++ ; step = step + ( - 1 - a [ i ] ) ; } else { positive ++ ; step = step + ( a [ i ] - 1 ) ; } } if ( negative % 2 == 0 ) { step = step + zero ; } else { if ( zero > 0 ) { step = step + zero ; } else { step = step + 2 ; } } return step ; } let a = [ 0 , - 2 , - 1 , - 3 , 4 ] ; let n = a . length ; document . write ( MinStep ( a , n ) ) ;