Remaining array element after repeated removal of last element and subtraction of each element from next adjacent element

Given an array arr[] consisting of N integers, the task is to find the remaining array element after subtracting each element from its next adjacent element and removing the last array element repeatedly.
Examples:
Input: arr[] = {3, 4, 2, 1}
Output: 4
Explanation:
Operation 1: The array arr[] modifies to {4 – 3, 2 – 4, 1 – 2} = {1, -2, -1}.
Operation 2: The array arr[] modifies to {-2 – 1, -1 + 2} = {-3, 1}.
Operation 3: The array arr[] modifies to {1 + 3} = {4}.
Therefore, the last remaining array element is 4.Input: arr[] = {1, 8, 4}
Output: -11
Explanation:
Operation 1: The array arr[] modifies to {1 – 8, 4 – 8} = {7, -4}.
Operation 2: The array arr[] modifies to {-4 – 7 } = {-11}.
Therefore, the last remaining array element is -11.
Naive Approach: The simplest approach is to traverse the array until its size reduces to 1 and perform the given operations on the array. After completing the traversal, print the remaining elements. Below is the implementation of the above approach.
C++
#include <iostream>#include <vector>Â
using namespace std;Â
// Function to find the remaining array elementint findRemainingElement(vector<int>& arr) {Â Â Â Â int n = arr.size();Â
    while (n > 1) {        for (int i = 0; i < n - 1; i++) {            arr[i] = arr[i+1] - arr[i];        }        n--;    }Â
    return arr[0];}Â
// Driver codeint main() {    // Given input    vector<int> arr = {3, 4, 2, 1};Â
    // Function call    int remainingElement = findRemainingElement(arr);Â
    // Print the remaining element    cout << "Remaining element: " << remainingElement << endl;Â
    return 0;} |
Java
import java.util.*;Â
public class Main {    // Function to find the remaining array element    public static int    findRemainingElement(List<Integer> arr)    {        int n = arr.size();Â
        while (n > 1) {            for (int i = 0; i < n - 1; i++) {                arr.set(i, arr.get(i + 1) - arr.get(i));            }            n--;        }Â
        return arr.get(0);    }Â
    // Driver code    public static void main(String[] args)    {        // Given input        List<Integer> arr = Arrays.asList(3, 4, 2, 1);Â
        // Function call        int remainingElement = findRemainingElement(arr);Â
        // Print the remaining element        System.out.println("Remaining element: "                           + remainingElement);    }}// This code is contributed by user_dtewbxkn77n |
Python3
# Python3 impelementationdef find_remaining_element(arr):Â Â Â Â n = len(arr)Â
    while n > 1:        for i in range(n - 1):            arr[i] = arr[i+1] - arr[i]        n -= 1Â
    return arr[0]Â
# Driver codearr = [3, 4, 2, 1]Â
# Function callremaining_element = find_remaining_element(arr)Â
# Print the remaining elementprint("Remaining element:", remaining_element)Â
# written by kk |
C#
using System;using System.Collections.Generic;Â
class MainClass {    // Function to find the remaining array element    static int FindRemainingElement(List<int> arr) {        int n = arr.Count;Â
        while (n > 1) {            for (int i = 0; i < n - 1; i++) {                arr[i] = arr[i+1] - arr[i];            }            n--;        }Â
        return arr[0];    }Â
    // Driver code    static void Main() {        // Given input        List<int> arr = new List<int> {3, 4, 2, 1};Â
        // Function call        int remainingElement = FindRemainingElement(arr);Â
        // Print the remaining element        Console.WriteLine("Remaining element: " + remainingElement);    }}// This code is contributed by sarojmcy2e |
Javascript
function findRemainingElement(arr) {Â Â Â Â let n = arr.length;Â
    while (n > 1) {        for (let i = 0; i < n - 1; i++) {            arr[i] = arr[i+1] - arr[i];        }        n--;    }Â
    return arr[0];}Â
// Given inputlet arr = [3, 4, 2, 1];Â
// Function calllet remainingElement = findRemainingElement(arr);Â
// Print the remaining elementconsole.log("Remaining element: " + remainingElement); |
Remaining element: 4
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the following observations:
- Suppose the given array is arr[] = {a, b, c, d}. Then, performing the operations:
- Now, suppose the array arr[] = {a, b, c, d, e}. Then, performing the operations:
- From the above two observations, it can be concluded that the answer is the sum of multiplication of coefficients of terms in the expansion of (x – y)(N – 1) and each array element arr[i].
- Therefore, the idea is to find the sum of the array arr[] after updating each array element as (arr[i]* (N – 1)C(i-1)* (-1)i).
Follow the steps below to solve the problem:
- Traverse the array arr[] and update arr[i] as arr[i] = arr[i]* (N – 1)C(i – 1)* (-1)i after calculating the NCr using Pascal’s triangle.
- Print the sum of array arr[].
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include "bits/stdc++.h"using namespace std;Â
// Function to find the last remaining// array element after performing// the given operations repeatedlyint lastElement(const int arr[], int n){    // Stores the resultant sum    int sum = 0;Â
    int multiplier = n % 2 == 0 ? -1 : 1;Â
    // Traverse the array    for (int i = 0; i < n; i++) {Â
        // Increment sum by arr[i]        // * coefficient of i-th term        // in (x - y) ^ (N - 1)        sum += arr[i] * multiplier;Â
        // Update multiplier        multiplier            = multiplier * (n - 1 - i)              / (i + 1) * (-1);    }Â
    // Return the resultant sum    return sum;}Â
// Driver Codeint main(){Â Â Â Â int arr[] = { 3, 4, 2, 1 };Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â Â Â Â cout << lastElement(arr, N);Â
    return 0;} |
Java
/*package whatever //do not write package name here */Â
import java.io.*;Â
class GFG {Â
    // Function to find the last remaining    // array element after performing    // the given operations repeatedly    public static int lastElement(int arr[], int n)    {        // Stores the resultant sum        int sum = 0;Â
        int multiplier = n % 2 == 0 ? -1 : 1;Â
        // Traverse the array        for (int i = 0; i < n; i++) {Â
            // Increment sum by arr[i]            // * coefficient of i-th term            // in (x - y) ^ (N - 1)            sum += arr[i] * multiplier;Â
            // Update multiplier            multiplier                = multiplier * (n - 1 - i) / (i + 1) * (-1);        }Â
        // Return the resultant sum        return sum;    }Â
    // Driver Code    public static void main(String[] args)    {        int arr[] = { 3, 4, 2, 1 };        int N = 4;        System.out.println(lastElement(arr, N));    }}Â
// This code is contributed by aditya7409. |
Python3
# Python 3 program for the above approachÂ
# Function to find the last remaining# array element after performing# the given operations repeatedlydef lastElement(arr, n):       # Stores the resultant sum    sum = 0    if n % 2 == 0:        multiplier = -1    else:        multiplier = 1Â
    # Traverse the array    for i in range(n):               # Increment sum by arr[i]        # * coefficient of i-th term        # in (x - y) ^ (N - 1)        sum += arr[i] * multiplierÂ
        # Update multiplier        multiplier = multiplier * (n - 1 - i) / (i + 1) * (-1)Â
    # Return the resultant sum    return sumÂ
# Driver Codeif __name__ == '__main__':Â Â Â Â arr = [3, 4, 2, 1]Â Â Â Â N = len(arr)Â Â Â Â print(int(lastElement(arr, N)))Â Â Â Â Â Â Â Â Â # This code is contributed by SURENDRA_GANGWAR. |
Javascript
<script>// JavaScript program for the above approachÂ
// Function to find the last remaining// array element after performing// the given operations repeatedlyfunction lastElement(arr, n){Â
    // Stores the resultant sum    let sum = 0;    let multiplier = n % 2 == 0 ? -1 : 1;Â
    // Traverse the array    for (let i = 0; i < n; i++)     {Â
        // Increment sum by arr[i]        // * coefficient of i-th term        // in (x - y) ^ (N - 1)        sum += arr[i] * multiplier;Â
        // Update multiplier        multiplier            = multiplier * (n - 1 - i)            / (i + 1) * (-1);    }Â
    // Return the resultant sum    return sum;}Â
// Driver Code    let arr = [ 3, 4, 2, 1 ];    let N = arr.length;    document.write(lastElement(arr, N));Â
// This code is contributed by Surbhi Tyagi.</script> |
C#
// C# program for the above approach using System;class GFG {Â
  // Function to find the last remaining  // array element after performing  // the given operations repeatedly  public static int lastElement(int[] arr, int n)  {         // Stores the resultant sum    int sum = 0;Â
    int multiplier = n % 2 == 0 ? -1 : 1;Â
    // Traverse the array    for (int i = 0; i < n; i++) {Â
      // Increment sum by arr[i]      // * coefficient of i-th term      // in (x - y) ^ (N - 1)      sum += arr[i] * multiplier;Â
      // Update multiplier      multiplier        = multiplier * (n - 1 - i) / (i + 1) * (-1);    }Â
    // Return the resultant sum    return sum;  }Â
  // Driver code  static void Main()  {    int[] arr = { 3, 4, 2, 1 };    int N = 4;    Console.WriteLine(lastElement(arr, N));  }}Â
// This code is contributed by susmitakundugoaldanga. |
4
Time Complexity: O(N)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!




