C ++中三个数的最大乘积

假设我们有一个整数数组;我们必须找到三个乘积最大的数字,然后返回最大乘积。

因此,如果输入类似于[1,1,2,3,3],则输出将为18,因为三个元素均为[2,3,3]。

为了解决这个问题,我们将遵循以下步骤-

  • 对数组数字进行排序

  • l:= nums的大小

  • a:= nums [1-1],b:= nums [1-2],c:= nums [1-3],d:= nums [0],e:= nums [1]

  • 返回a * b * c和d * e * a的最大值

例 

让我们看下面的实现以更好地理解-

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
   int maximumProduct(vector<int>& nums) {
      sort(nums.begin(), nums.end());
      int l = nums.size();
      int a = nums[l - 1], b = nums[l - 2], c = nums[l - 3], d = nums[0], e = nums[1];
      return max(a * b * c, d * e * a);
   }
};
main(){
   Solution ob;
   vector<int> v = {1,1,2,3,3};
   cout << (ob.maximumProduct(v));
}

输入项

{1,1,2,3,3}

输出结果

18