Count of ways to make Array sum even by removing only one element

Given an array arr[] positive integers, the task is to find the number of ways to convert the array sum even if we are allowed to remove only one element.

Examples:

Input: arr[] = { 1, 3, 3, 2 }
Output: 3
Explanation:
1. Remove 1, then sum is 3 + 3 + 2 = 8.
2. Remove 3, then sum is 1 + 3 + 2 = 6.
3. Remove 3, then sum is 1 + 3 + 2 = 6.

Input: arr[] = { 4, 8, 3, 3, 6 }
Output: 3
Explanation:
1. Remove 4, then sum is 8 + 3 + 3 + 6 = 20.
2. Remove 8, then sum is 4 + 3 + 3 + 6 = 16.
3. Remove 6, then sum is 4 + 8 + 3 + 3 = 18.

Approach: The key observation to the above problem statement is:



  1. If we have an odd number of odd elements then the sum is always odd then we have to remove one odd number from the array arr[] to make the sum even. Since we have to remove one element, therefore, the total number of ways of making the sum even is the count of odd elements in the array arr[].
  2. If we have an even number of odd elements then the sum is always even. Since we have to remove one element to make the sum even, therefore, the total number of ways of making the sum even is the count of even elements in the array arr[]

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to find a number of ways
// to make array element sum even by
// removing one element
int find_num_of_ways(int arr[], int N)
{
    int count_even = 0, count_odd = 0;
  
    // Finding the count of even
    // and odd elements
    for (int i = 0; i < N; i++) {
        if (arr[i] % 2) {
            count_odd++;
        }
        else {
            count_even++;
        }
    }
  
    // If count_odd is odd then
    // no. of ways is count_odd
    if (count_odd % 2) {
        return count_odd;
    }
  
    // Else no. of ways is count_even
    else {
        return count_even;
    }
}
  
// Driver Code
int main()
{
  
    // Given array arr[]
    int arr[] = { 1, 3, 3, 2 };
    int N = sizeof(arr) / sizeof(arr[0]);
  
    // Function Call
    cout << find_num_of_ways(arr, N);
    return 0;
}

chevron_right


Output:

3

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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.