要删除的最小元素,使得相邻元素的总和始终是偶数
给定一个包含 N 个整数的数组。任务是消除最小数量的元素,使得在结果数组中任何两个相邻值的总和是偶数。
例子:
Input : arr[] = {1, 2, 3}
Output : 1
Remove 2 from the array.
Input : arr[] = {1, 3, 5, 4, 2}
Output : 2
Remove 4 and 2.
方法:两个数字的总和是偶数,即使它们都是奇数或它们都是偶数。这意味着对于具有不同奇偶性的每一对连续数字,消除其中一个。
因此,要使相邻元素之和为偶数,所有元素都应该是奇数或偶数。所以下面的贪心算法有效:
- 按顺序浏览所有元素。
- 计算数组中的奇数和偶数元素。
- 返回最小计数。
下面是上述方法的实现:
C++
// C++ implementation of the above approach
#include
using namespace std;
// Function to find minimum number of eliminations
// such that sum of all adjacent elements is even
int min_elimination(int n, int arr[])
{
int countOdd = 0;
// Stores the new value
for (int i = 0; i < n; i++)
// Count odd numbers
if (arr[i] % 2)
countOdd++;
// Return the minimum of even and
// odd count
return min(countOdd, n - countOdd);
}
// Driver code
int main()
{
int arr[] = { 1, 2, 3, 7, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << min_elimination(n, arr);
return 0;
}
Java
// Java implementation of the above approach
class GFG
{
// Function to find minimum number of
// eliminations such that sum of all
// adjacent elements is even
static int min_elimination(int n, int arr[])
{
int countOdd = 0;
// Stores the new value
for (int i = 0; i < n; i++)
// Count odd numbers
if (arr[i] % 2 == 1)
countOdd++;
// Return the minimum of even
// and odd count
return Math.min(countOdd, n - countOdd);
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 1, 2, 3, 7, 9 };
int n = arr.length;
System.out.println(min_elimination(n, arr));
}
}
// This code is contributed by Code_Mech
Python3
# Python 3 implementation of the
# above approach
# Function to find minimum number of
# eliminations such that sum of all
# adjacent elements is even
def min_elimination(n, arr):
countOdd = 0
# Stores the new value
for i in range(n):
# Count odd numbers
if (arr[i] % 2):
countOdd += 1
# Return the minimum of even and
# odd count
return min(countOdd, n - countOdd)
# Driver code
if __name__ == '__main__':
arr = [1, 2, 3, 7, 9]
n = len(arr)
print(min_elimination(n, arr))
# This code is contributed by
# Surendra_Gangwar
C#
// C# implementation of the above approach
using System;
class GFG
{
// Function to find minimum number of
// eliminations such that sum of all
// adjacent elements is even
static int min_elimination(int n, int[] arr)
{
int countOdd = 0;
// Stores the new value
for (int i = 0; i < n; i++)
// Count odd numbers
if (arr[i] % 2 == 1)
countOdd++;
// Return the minimum of even
// and odd count
return Math.Min(countOdd, n - countOdd);
}
// Driver code
public static void Main()
{
int[] arr = { 1, 2, 3, 7, 9 };
int n = arr.Length;
Console.WriteLine(min_elimination(n, arr));
}
}
// This code is contributed by Code_Mech
PHP
Javascript
输出:
1
时间复杂度: O(N)
辅助空间: O(1)