在C ++中最小删除使数组和成为奇数
问题陈述
给定N个整数的数组arr[]。我们需要编写一个程序来查找需要从数组中删除的最小元素数,以便剩余元素的总和为奇数。
示例
如果输入数组为{10,20,30,5,7},那么我们需要删除一个元素(即5或7)以使数组和为奇数
算法
1. Sum of any number of even numbers is always even 2. Sum of odd numbers of odd numbers is always odd 3. Sum of odd numbers of even times is always even 4. Count the number of odd elements in the array. If the count of odd elements in the array is even, then we need to remove single element from the array but if the count of odd elements in the array is odd then there is no need to remove any element
示例
#include <bits/stdc++.h>
using namespace std;
int getMinRemovals(int *arr, int n) {
int cnt = 0;
for (int i = 0; i < n; ++i) {
if (arr[i] % 2 == 1) {
++cnt;
}
}
return (cnt % 2 == 0) ? 1 : 0;
}
int main() {
int arr[] = {10, 20, 30, 5, 7};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Minimum required removals = " <<
getMinRemovals(arr, n) << endl;
return 0;
}当您编译并执行上述程序时。它产生以下输出
输出结果
Minimum required removals = 1
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短