promotion for 35 years coder-Day07-求无序数组三元素乘积最大值

思路:

当把元素排序后,分为三种情况

(1)元素全正:最大三个元素相乘即可

(2)元素全负:最大三个元素相乘即可

(3)有正有负:必须保证最后乘积为正才可能最大,最大值只可能有两种情况

最大三个数相乘,负数最小两个数相乘再和最大的数相乘

综上,结果就是max(min1*min2*max1, max1*max2*max3)

所以无需排序,只需遍历一遍找到上述5个值即可

#include <iostream>
using namespace std;

int getMax(int *pArray, int len)
{
    int min1 = 2147483647, min2 = 2147483647;
    int max1 = -2147483648, max2 = -2147483648, max3 = -2147483648;
    
    for (int i = 0; i < len; i++)
    {
        if (pArray[i] < min1)
        {
            min2 = min1;
            min1 = pArray[i];
        }
        else if (pArray[i] < min2)
        {
            min2 = pArray[i];
        }
        
        if (pArray[i] > max1)
        {
            max3 = max2;
            max2 = max1;
            max1= pArray[i];
        }
        else if (pArray[i] > max2)
        {
            max3 = max2;
            max2= pArray[i];
        }
        else if (pArray[i] > max3)
        {
            max3= pArray[i];
        }
    }
    
    int res1 = min1 * min2 * max1;
    int res2 = max1 * max2 * max3;
    
    return res1 > res2 ? res1 : res2;
}

int main() {
    int test1[] = {6,3,12,56,23,1};
    int expect = 12 * 56 * 23;
    int ret = getMax(test1, 6);
    cout  << "ret = " << ret << ", answer is " << expect  << endl;
    
    int test2[] = {-3,-12,-5,-87,-23};
    expect = (-3) * (-5) * (-12);
    ret = getMax(test2, 5);
    cout  << "ret = " << ret << ", answer is " << expect  << endl;
    
    int test3[] = {2,5,78,-12,34,-8,-98};
    expect = (-98) * (-12) * 78;
    ret = getMax(test3, 7);
    cout  << "ret = " << ret << ", answer is " << expect  << endl;
    
    
    
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值