
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add Minimum Number to Array for Even Sum in C++
Suppose there is an array with some numbers. We have to tell minimum how many numbers will be added with it to make the sum of the elements even. The number must be greater than 0. So if the sum of the elements is odd, we will add 1, but if the sum is already even, then we will add 2 with it to make it even.
Algorithm
addMinNumber(arr)
begin s := 0 for each element e from arr, do s := e + s done if s is even, then return 2, otherwise 1 end
Example
#include<iostream> using namespace std; int addMinNumber(int arr[], int n) { int sum = 0; for(int i = 0; i<n; i++) { sum += arr[i]; } return (sum % 2)? 1 : 2; } main() { int arr[] = {5, 8, 4, 7, 5}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Minimum " << addMinNumber(arr, n) << " should be added"; }
Output
Minimum 1 should be added
Advertisements