用 C++ 將陣列總和變為偶數所需的最小移除數


問題表述

給定一個包含 N 個整數的陣列 arr[]。我們需要編寫一個程式來查詢陣列中需要移除的最小元素數,以便剩餘元素的總和為偶數。

示例

如果輸入陣列為 {10, 20, 30, 5},則我們需要移除一個元素,即 5,才能使陣列總和為偶數

演算法

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 do not need to remove any element from the array but if the count of odd elements in the array is odd then by removing any one of the odd elements from the array

示例

 動態演示

#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) ? 0 : 1;
}
int main() {
   int arr[] = {10, 20, 30, 5};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Minimum required removals = " << getMinRemovals(arr, n) << endl;
   return 0;
}

當你編譯並執行上述程式時,它將生成以下輸出

輸出

Minimum required removals = 1

更新日期: 2019-12-23

171 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告