Remaining array element after repeated removal of last element and subtraction of each element from next adjacent element | Function to find the last remaining array element after performing the given operations repeatedly ; Stores the resultant sum ; Traverse the array ; Increment sum by arr [ i ] * coefficient of i - th term in ( x - y ) ^ ( N - 1 ) ; Update multiplier ; Return the resultant sum ; Driver Code
function lastElement ( arr , n ) { let sum = 0 ; let multiplier = n % 2 == 0 ? - 1 : 1 ; for ( let i = 0 ; i < n ; i ++ ) { sum += arr [ i ] * multiplier ; multiplier = multiplier * ( n - 1 - i ) / ( i + 1 ) * ( - 1 ) ; } return sum ; } let arr = [ 3 , 4 , 2 , 1 ] ; let N = arr . length ; document . write ( lastElement ( arr , N ) ) ;