C++中可新增到集合的最大差值元素


根據題目,我們得到一個集合arr[n],其中n是集合中整數元素的數量,任務是找到需要相加才能得到集合中元素的最大差值元素。換句話說,差值應為|a-b|的形式,其中'a'和'b'都屬於集合,且它們的差值不應是最小的。因此,我們將計算集合中不同的且最大的差值的數量。讓我們透過一個例子來了解問題及其解決方案。

輸入 − 集合 = {1, 5}

輸出 − 可新增到集合的最大差值元素為:1

解釋 − 集合中只有一個差值,即|1-5| = 4

輸入 − 集合 = {2, 7, 1, 9}

輸出 − 最大差值

可新增到集合的元素為:5

解釋 − 集合中的差值如下:

|2-7| = 5
|7-1| = 6
|1-9| = 8
|2-9| = 7
|7-9| = 2

下面程式中使用的演算法如下:

  • 使用整數陣列arr[n]儲存集合的值。

  • 在maximum()函式中,執行步驟3到6。

  • 宣告元素ele、temp、val並將它們的值設定為arr[0]

  • 迴圈i從1到陣列大小,步長為1。

    • 求陣列中所有元素的最大公約數。

    • 將temp設定為temp或arr[i]中的最大值。

  • 將total設定為temp/val,將max設定為total和size的差值。

  • 返回並列印max。

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
//function to find maximum difference element
int maximum(int arr[], int size){
   int ele = arr[0];
   int val = ele;
   int temp = ele;
   for (int i = 1; i < size; i++){
      val = __gcd(val, arr[i]);
      temp = max(temp, arr[i]);
   }
   int total = temp / val;
   int max = total - size;
   return max;
}
int main(){
   int arr[] = { 2, 7, 1, 9};
   int size = sizeof(arr) / sizeof(arr[0]);
   cout<<"Maximum difference elements that can added to a set is: "<<maximum(arr, size);
   return 0;
}

輸出

如果我們執行以上程式碼,我們將得到以下輸出:

Maximum difference elements that can added to a set is: 5

更新於:2020年8月14日

81 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始
廣告