给定一个由N个整数组成的数组Arr []。任务是找到需要从数组中删除的元素的最小数量,以使剩余元素的总和为奇数。考虑到至少有一个奇数。
例子:
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.
方法:解决此问题的想法是首先回忆ODD和EVEN的以下属性:
- 奇数+奇数=偶数
- 奇数+偶数=奇数
- 偶数+偶数=偶数
- 奇数*偶数=偶数
- 偶数*偶数=偶数
- 奇数*奇数=奇数
因为任何数量的偶数之和是偶数。因此,偶数的计数无关紧要。
并且奇数的奇数之和总是奇数。因此,要使数组和为奇数,奇数的计数必须为奇数。
因此,计算奇数的数量,然后检查计数是否为奇数,则无需删除。否则计数为偶数,则需要删除1个奇数。
下面是上述方法的实现:
C++
// C++ implementation of the above approach
#include
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;
}
Java
// Java implementation of the above approach
class GfG
{
// Function to find minimum removals
static 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
public static void main(String[] args)
{
int arr[] = { 1, 2, 3, 5, 1 };
int n = arr.length;
System.out.println(findCount(arr, n));
}
}
// This code is contributed by
// Prerna Saini
Python3
# Python3 implementation of the
# above approach
# Function to find minimum removals
def findCount(arr, n) :
# Count odd numbers
countOdd = 0;
for i in range(n) :
if (arr[i] % 2 == 1) :
countOdd += 1;
# If the counter is odd return 0
# otherwise return 1
if (countOdd % 2 == 0) :
return 1;
else :
return 0;
# Driver Code
if __name__ == "__main__" :
arr = [ 1, 2, 3, 5, 1 ];
n = len(arr) ;
print(findCount(arr, n));
# This code is contributed by Ryuga
C#
// C# implementation of the approach
using System;
class GfG
{
// Function to find minimum removals
static 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
public static void Main(String[] args)
{
int []arr = { 1, 2, 3, 5, 1 };
int n = arr.Length;
Console.WriteLine(findCount(arr, n));
}
}
// This code has been contributed by 29AjayKumar
PHP
输出:
1