Count Remaining Elements After Even Sum Operations in an Array

By | November 25, 2024

Given an array of size N. The task is to choose an arbitrary pair of elements from the Array such that their sum is even, delete these two elements from the Array and insert their sum into the sequence instead. And finally, count the number of elements remaining in the array at the end.

Examples:

Input:N = 2, Arr[] = {1, 2}
Output: Remaining elements = 2
(As we can not choose pair of elements whose sum is even so, elements remaining is 2)

Input: N = 5, Arr[] = {7, 2, 4, 3, 6}
Output: Remaining elements = 1
(As we can choose elements 7 and 3 in the first step, delete them and insert 10 in the sequence.
Now, array becomes Arr[] = {10, 2, 4, 6}
Now all its elements are even and we can choose any two elements on each of the following steps
until the array contains only one element.

Approach:

  1. Start transversing the array and find the sum of all elements.
  2. Now, If sum is even or the value of N is equal to 1 then return 1, Else return 2

Below is the implementation of the above approach:

// C++ implementation of above approach
#include <bits/stdc++.h>
using namespace std;

// function that calculates the 
// Remaining element in the array
int remainingElements(int Arr[], int N)
{
    int sum = 0;
    
    for(int i = 0; i < N; i++){
        sum += Arr[i];
    }
    
    if(sum % 2 == 0 || N == 1)
        return 1;
    else
        return 2;
}

// Driver Code
int main()
{
  
    int Arr[] = {5, 24, 32, 45};
    int N = sizeof(Arr) / sizeof(Arr[0]);
    
    // Calling function.
    int remaining = remainingElements(Arr, N);
    
    cout << "Remaining element = " << remaining;
    
    return 0;
}

Output:

Remaining elements = 1
Author: Mithlesh Upadhyay

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.