Open In App

Reduce the array by replacing 1st and middle element with sum and difference alternatively

Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of size N, the task is to find the last remaining element of the array after consecutively removing the 1st and the middle element of the array and alternatively appending their sum and difference at the end of the array.

Examples:

Input: A = {2, 4, 1, 5, 7}
Output: 5
Explanation: During the 1st iteration, remove arr[0] and arr[2] from the array 
and append their sum (2 + 1 = 3) to the end of the array. 
Hence, arr[] = {4, 5, 7, 3}. 
Again repeat the same process and remove arr[0] and arr[2] from the array 
and now append their difference (7 – 4) = 3. 
Hence, arr[] = {5, 3, 3}.
 After the next iteration, array will become arr[] = {3, 8}. 
And finally after the last iteration, arr[] = {5} which is the last required value.

Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Output: 15

 

Approach: The given problem is an implementation-based problem and can be solved by repetitively following the given steps:

  • Maintain a variable op, which stores the count of operation.
  • Remove the first and middle element of the array till its size is more than 1 and append the array with their addition or subtraction according to the op (i., e if op is even, perform addition, otherwise perform subtraction).

Below is the implementation of the above approach:

C++




// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the last element
// in array after the given operations
int lastElement(vector<int>& arr)
{
 
    // Maintain operation count
    int op = 0, x = 0;
 
    // Loop until array has more
    // than 1 element in it
    while (arr.size() != 1) {
 
        // Stores middle index
        int mid = arr.size() / 2;
 
        // For even iterations perform
        // addition otherwise subtraction
        if (op % 2 == 0) {
            x = arr[mid] + arr[0];
            arr.erase(arr.begin() + mid);
            arr.erase(arr.begin());
        }
        else {
            x = arr[mid] - arr[0];
            arr.erase(arr.begin() + mid);
            arr.erase(arr.begin());
        }
 
        // Append in the end
        arr.push_back(x);
 
        // Increment operation count
        op += 1;
    }
 
    // Return Answer
    return arr[0];
}
 
// Driver Code
int main()
{
    vector<int> arr = { 2, 4, 1, 5, 7 };
    cout << lastElement(arr);
 
    return 0;
}
 
    // This code is contributed by rakeshsahni


Java




// Java program of the above approach
import java.util.*;
 
class GFG{
 
// Function to find the last element
// in array after the given operations
static int lastElement(Vector<Integer> arr)
{
 
    // Maintain operation count
    int op = 0, x = 0;
 
    // Loop until array has more
    // than 1 element in it
    while (arr.size() != 1) {
 
        // Stores middle index
        int mid = arr.size() / 2;
 
        // For even iterations perform
        // addition otherwise subtraction
        if (op % 2 == 0) {
            x = arr.get(mid) + arr.get(0);
            arr.remove(mid);
            arr.remove(0);
        }
        else {
            x = arr.get(mid) - arr.get(0);
            arr.remove(mid);
            arr.remove(0);
        }
 
        // Append in the end
        arr.add(x);
 
        // Increment operation count
        op += 1;
    }
 
    // Return Answer
    return arr.get(0);
}
 
// Driver Code
public static void main(String[] args)
{
    Integer []arr = { 2, 4, 1, 5, 7 };
    Vector<Integer> v = new Vector<Integer>();
    Collections.addAll(v, arr);
    System.out.print(lastElement(v));
 
}
}
 
// This code is contributed by shikhasingrajput


Python3




# Python program of the above approach
 
# Function to find the last element
# in array after the given operations
def lastElement(arr):
 
    # Maintain operation count
    op = 0
 
    # Loop until array has more
    # than 1 element in it
    while len(arr) != 1:
 
        # Stores middle index
        mid = len(arr)//2
 
        # For even iterations perform
        # addition otherwise subtraction
        if op % 2 == 0:
            x = arr.pop(mid) + arr.pop(0)
        else:
            x = arr.pop(mid) - arr.pop(0)
 
        # Append in the end
        arr.append(x)
 
        # Increment operation count
        op += 1
 
    # Return Answer
    return arr[0]
 
 
# Driver Code
if __name__ == "__main__":
    arr = [2, 4, 1, 5, 7]
    print(lastElement(arr))


C#




// C# program of the above approach
using System;
using System.Collections.Generic;
 
public class GFG{
 
  // Function to find the last element
  // in array after the given operations
  static int lastElement(List<int> arr)
  {
 
    // Maintain operation count
    int op = 0, x = 0;
 
    // Loop until array has more
    // than 1 element in it
    while (arr.Count != 1) {
 
      // Stores middle index
      int mid = arr.Count / 2;
 
      // For even iterations perform
      // addition otherwise subtraction
      if (op % 2 == 0) {
        x = arr[mid] + arr[0];
        arr.RemoveAt(mid);
        arr.RemoveAt(0);
      }
      else {
        x = arr[mid] - arr[0];
        arr.RemoveAt(mid);
        arr.RemoveAt(0);
      }
 
      // Append in the end
      arr.Add(x);
 
      // Increment operation count
      op += 1;
    }
 
    // Return Answer
    return arr[0];
  }
 
  // Driver Code
  public static void Main(String[] args)
  {
    int []arr = { 2, 4, 1, 5, 7 };
    List<int> v = new List<int>(arr);
    Console.Write(lastElement(v));
 
  }
}
 
// This code is contributed by shikhasingrajput


Javascript




<script>
       // JavaScript code for the above approach
 
       // Function to find the last element
       // in array after the given operations
       function lastElement(arr) {
 
           // Maintain operation count
           let op = 0, x = 0;
 
           // Loop until array has more
           // than 1 element in it
           while (arr.length != 1) {
 
               // Stores middle index
               let mid = Math.floor(arr.length / 2);
 
               // For even iterations perform
               // addition otherwise subtraction
               if (op % 2 == 0) {
                   x = arr[mid] + arr[0];
                   let p1 = arr.slice(1, mid)
                   let p2 = arr.slice(mid + 1)
                   arr = [...p1.concat(p2)];
               }
               else {
                   x = arr[mid] - arr[0];
                   let p1 = arr.slice(1, mid)
                   let p2 = arr.slice(mid + 1)
                   arr = [...p1.concat(p2)];
 
 
               }
 
               // Append in the end
               arr.push(x);
 
               // Increment operation count
               op = op + 1;
           }
 
           // Return Answer
           return arr[0];
       }
 
       // Driver Code
 
       let arr = [2, 4, 1, 5, 7];
       document.write(lastElement(arr));
 
    // This code is contributed by Potta Lokesh
   </script>


Output

5

Time Complexity: O(N2)
Auxiliary Space: O(1)



Last Updated : 24 Feb, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads