Minimum Removals to Make Array Sum Odd in C++



In this article, we have an array arr[] of N integers. Our task is to write a program to find the minimum number of elements needed to be removed from the given array so that the sum of the remaining elements is odd.

Example

The following example demonstrates the minimum number of elements we need to remove from the array for the sum to be odd:

Input:
arr = {12, 23, 40, 53, 17}
Output: 0
Input:
arr = {20, 11, 13, 40, 24}
Output: 1

The explanation of the above example is as follows:

In the above example,
arr = {20, 11, 13, 40, 24}
sum of elements = 20+11+13+40+24 = 108 
=>Even, 1 removal needed

Conditions for Sum to be Odd

Here are some of the conditions for a sum to be odd:

  • When all the elements are even, their sum is also even. So, we need to remove 1 even element.
  • An odd number of odd numbers when added gives an odd number. Example: 3+7+11 = 21
  • The summation of even times of odd numbers is an even number. Example: 3+7 = 10
  • The summation of one odd and one even is an odd number.

Steps to Make Array Sum Odd with Minimum Removals

Here are the steps for removing the minimum element from the array to make the array sum odd:

  • Iterate over all elements of the array using a for loop and check if the array elements are odd.
  • For each odd element increase the counter by 1. Check the value of the count after completing the for loop.
  • If the value of the count is odd then return 0(no removals), as a summation of the odd number of odds is an odd number.
  • If the value of the count is even, then return 1. It means 1 odd element to be removed.

C++ Program to Make Array Sum Odd with Minimum Removals

The following code implements the above steps for removing the minimal number of elements from the array for an odd array sum.

#include <bits/stdc++.h>
using namespace std;
int minRemove(int *arr, int n)
{
   int count = 0;
   for (int i = 0; i < n; ++i)
   {
      if (arr[i] % 2 == 1)
      {
         ++count;
      }
   }
   return (count % 2 == 1) ? 0 : 1;
}
int main()
{
   int arr[] = {1, 2, 4, 5, 1};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Given array is: ";
   for (int i = 0; i < n; ++i)
   {
      cout << arr[i] << " ";
   }
   cout << "\nMinimum required removals = " 
        << minRemove(arr, n) << endl;
   return 0;
}

The output of the above code is as follows:

Given array is: 1 2 4 5 1 
Minimum required removals = 0
Updated on: 2025-06-12T17:19:43+05:30

235 Views

Kickstart Your Career

Get certified by completing the course

Get Started