C++ 中三数的最大乘积


假设我们有一个整数数组;我们需要找出三个数,它们的乘积最大,然后返回乘积的最大值。

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

为解决这个问题,我们将按以下步骤操作 -

  • 对数组 nums 排序

  • l := nums 的大小

  • a := nums[l - 1], b := nums[l - 2], c := nums[l - 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

更新日期: 2020 年 6 月 11 日

662 次浏览

启动您的 职业

完成课程以获得认证

开始
广告
© . All rights reserved.