Count ways to make sum of odd and even indexed elements equal by removing an array element | Function to count array indices whose removal makes sum of odd and even indexed elements equal ; If size of the array is 1 ; If size of the array is 2 ; Stores sum of even - indexed elements of the given array ; Stores sum of odd - indexed elements of the given array ; Traverse the array ; If i is an even number ; Update sumEven ; If i is an odd number ; Update sumOdd ; Stores sum of even - indexed array elements till i - th index ; Stores sum of odd - indexed array elements till i - th index ; Stores count of indices whose removal makes sum of odd and even indexed elements equal ; Stores sum of even - indexed elements after removing the i - th element ; Stores sum of odd - indexed elements after removing the i - th element ; Traverse the array ; If i is an odd number ; Update currOdd ; Update newEvenSum ; Update newOddSum ; If i is an even number ; Update currEven ; Update newOddSum ; Update newEvenSum ; If newEvenSum is equal to newOddSum ; Increase the count ; If sum of even - indexed and odd - indexed elements is equal by removing the first element ; Increase the count ; If length of the array is an odd number ; If sum of even - indexed and odd - indexed elements is equal by removing the last element ; Increase the count ; If length of the array is an even number ; If sum of even - indexed and odd - indexed elements is equal by removing the last element ; Increase the count ; Driver Code
function cntIndexesToMakeBalance ( arr , n ) { if ( n == 1 ) { return 1 ; } if ( n == 2 ) return 0 ; let sumEven = 0 ; let sumOdd = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( i % 2 == 0 ) { sumEven += arr [ i ] ; } else { sumOdd += arr [ i ] ; } } let currOdd = 0 ; let currEven = arr [ 0 ] ; let res = 0 ; let newEvenSum = 0 ; let newOddSum = 0 ; for ( let i = 1 ; i < n - 1 ; i ++ ) { if ( i % 2 ) { currOdd += arr [ i ] ; newEvenSum = currEven + sumOdd - currOdd ; newOddSum = currOdd + sumEven - currEven - arr [ i ] ; } else { currEven += arr [ i ] ; newOddSum = currOdd + sumEven - currEven ; newEvenSum = currEven + sumOdd - currOdd - arr [ i ] ; } if ( newEvenSum == newOddSum ) { res ++ ; } } if ( sumOdd == sumEven - arr [ 0 ] ) { res ++ ; } if ( n % 2 == 1 ) { if ( sumOdd == sumEven - arr [ n - 1 ] ) { res ++ ; } } else { if ( sumEven == sumOdd - arr [ n - 1 ] ) { res ++ ; } } return res ; } let arr = [ 1 , 1 , 1 ] ; let n = arr . length ; document . write ( cntIndexesToMakeBalance ( arr , n ) ) ;