C++ 中陣列中三元組(大小為 3 的子序列)的最大乘積


在本教程中,我們將討論一個程式,用於在陣列中查詢三元組(大小為 3 的子序列)的最大乘積。

為此,我們將在其中提供一個整數陣列。我們的任務是找到具有最大乘積的該陣列中的三個元素

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
//finding the maximum product
int maxProduct(int arr[], int n){
   if (n < 3)
      return -1;
   int max_product = INT_MIN;
   for (int i = 0; i < n - 2; i++)
      for (int j = i + 1; j < n - 1; j++)
         for (int k = j + 1; k < n; k++)
            max_product = max(max_product, arr[i] * arr[j] * arr[k]);
         return max_product;
}
int main() {
   int arr[] = { 10, 3, 5, 6, 20 };
   int n = sizeof(arr) / sizeof(arr[0]);
   int max = maxProduct(arr, n);
   if (max == -1)
      cout << "No Triplet Exists";
   else
      cout << "Maximum product is " << max;
   return 0;
}

輸出

Maximum product is 1200

更新日期:09-Sep-2020

84 次瀏覽

職業

完成課程獲得認證

開始
廣告
© . All rights reserved.