Remaining array element after repeated removal of last element and subtraction of each element from next adjacent element | C ++ program for the above approach ; 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
#include " bits / stdc + + . h " NEW_LINE using namespace std ; int lastElement ( const int arr [ ] , int n ) { int sum = 0 ; int multiplier = n % 2 == 0 ? -1 : 1 ; for ( int i = 0 ; i < n ; i ++ ) { sum += arr [ i ] * multiplier ; multiplier = multiplier * ( n - 1 - i ) / ( i + 1 ) * ( -1 ) ; } return sum ; } int main ( ) { int arr [ ] = { 3 , 4 , 2 , 1 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << lastElement ( arr , N ) ; return 0 ; }