VOOZH about

URL: https://www.geeksforgeeks.org/dsa/add-minimum-number-to-an-array-so-that-the-sum-becomes-even/

⇱ Add minimum number to an array so that the sum becomes even - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Add minimum number to an array so that the sum becomes even

Last Updated : 19 Sep, 2023

Given an array, write a program to add the minimum number(should be greater than 0) to the array so that the sum of array becomes even.

Examples: 

Input : 1 2 3 4 5 6 7 8
Output : 2
Explanation : Sum of array is 36, so we 
add minimum number 2 to make the sum even.

Input : 1 2 3 4 5 6 7 8 9
Output : 1

Method 1 (Computing Sum). We calculate the sum of all elements of the array, then we can check if the sum is even minimum number is 2, else minimum number is 1. This method can cause overflow if sum exceeds allowed limit.

Method 2. Instead of calculating the sum of numbers, we keep the count of odd number of elements in the array. If count of odd numbers present is even we return 2, else we return 1. 

For example - Array contains : 1 2 3 4 5 6 7 
Odd number counts is 4. And we know that the sum of even numbers of odd number is even. And sum of even number is always even (that is why, we don't keep count of even numbers). 

Implementation:


Output
1n

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

Method 3. We can also improve the 2 method, we don't need to keep count of number of odd elements present. We can take a boolean variable (initialized as 0). Whenever we find the odd element in the array we perform the NOT(!) operation on the boolean variable. This logical operator inverts the value of the boolean variable (meaning if it is 0, it converts the variable to 1 and vice-versa). 

For example - Array contains : 1 2 3 4 5 
Explanation : variable initialized as 0. 

Traversing the array 

  • 1 is odd, applying NOT operation in variable, now variable becomes 1. 
  • 2 is even, no operation. 
  • 3 is odd, applying NOT operation in variable, now variable becomes 0. 
  • 4 is even, no operation. 
  • 5 is odd, applying NOT operation in variable, now variable becomes 1.

If variable value is 1 it means odd number of odd elements are present, minimum number to make sum of elements even is by adding 1. 
Else minimum number is 2.

Implementation:


Output
1n

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

Exercise : 
Find the minimum number required to make the sum of elements odd.

Comment
Article Tags: