Minimum removals to make array sum odd

Given an array Arr[] of N integers. The task is to find minimum number of elements needed to be removed from the array, so that sum of remaining elements is odd. Considering there is atleast one odd number.

Examples:

Input:  arr[] = {1, 2, 3, 4}
Output: 1
Remove 1 to make array sum odd.

Input: arr[] =  {4, 2, 3, 4}
Output: 0
Sum is already odd.

Approach: The idea to solve this problem is to first recall the below properties of ODDs and EVENs:

  • odd + odd = even
  • odd + even = odd
  • even + even = even
  • odd * even = even
  • even * even = even
  • odd * odd = odd

As the sum of any number of even numbers is even. So the count of even doesn’t matter.
And the sum of odd number of odd number is always odd. So to make array sum odd, count of odd numbers must be odd.
So, count the number of odd numbers and check if the count is odd then no removals required. Else the count is even then 1 odd number needs to be removed.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the above approach
#include <iostream>
using namespace std;
  
// Function to find minimum removals
int findCount(int arr[], int n)
{
    // Count odd numbers
    int countOdd = 0;
    for (int i = 0; i < n; i++)
        if (arr[i] % 2 == 1)
            countOdd++;
  
    // If the counter is odd return 0
    // otherwise return 1
    if (countOdd % 2 == 0)
        return 1;
    else
        return 0;
}
  
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 5, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    cout << findCount(arr, n);
  
    return 0;
}

chevron_right


Output:

1


My Personal Notes arrow_drop_up