Smallest indexed array element required to be flipped to make sum of array equal to 0 | Function to find the smallest indexed array element required to be flipped to make sum of the given array equal to 0 ; Stores the required index ; Traverse the given array ; Flip the sign of current element ; Stores the sum of array elements ; Find the sum of the array ; Update sum ; If sum is equal to 0 ; Update pos ; Reset the current element to its original value ; Reset the value of arr [ i ] ; Driver Code
function smallestIndexArrayElementsFlip ( arr , N ) { var pos = - 1 ; var i , j ; for ( i = 0 ; i < N ; i ++ ) { arr [ i ] *= - 1 ; var sum = 0 ; for ( j = 0 ; j < N ; j ++ ) { sum += arr [ j ] ; } if ( sum == 0 ) { pos = i ; break ; } else { arr [ i ] *= - 1 ; } } return pos ; } var arr = [ 1 , 3 , - 5 , 3 , 4 ] ; var N = arr . length ; document . write ( smallestIndexArrayElementsFlip ( arr , N ) ) ;