【拼多多】最大乘积

[编程题] 最大乘积

时间限制:1秒

空间限制:32768K

给定一个无序数组,包含正数、负数和0,要求从中找出3个数的乘积,使得乘积最大,要求时间复杂度:O(n),空间复杂度:O(1)

输入描述:

无序整数数组A[n]

 

输出描述:

满足条件的最大乘积

 

输入例子1:

3 4 1 2

 

输出例子1:

24

Point:The result is the product of maximum three or the product of minimum two and maximum one. 

#include<iostream>
#include<algorithm>
#include<stdlib.h>
using namespace std;
long ma1,ma2,ma3;
long mi1,mi2;
void selection(long A[],long n)
{
    ma1=ma2=ma3=mi1=mi2=A[0];
    long temp;
    for(int i=1;i<n;i++)
    {
        if(A[i]>ma3){
            if(A[i]>ma1){
                temp=ma1;ma1=A[i];
                ma3=ma2;ma2=temp;
              }
            else if(A[i]>ma2){ temp=ma2;ma2=A[i];ma3=temp;}
            else { ma3=A[i];}
            }
        if(A[i]<mi2){
            if(A[i]<mi1){
                temp=mi1;mi1=A[i]; mi2=temp;
              }
            else { mi2=A[i];}
            }
        }
}

int main()
{
    long n;
    cin>>n;
    long *A=new long[n];
    for(long i=0;i<n;i++)cin>>*(A+i);
    selection(A,n);
    if(n==3)cout<<A[0]*A[1]*A[2]<<endl;
    else cout<<max(ma1*mi1*mi2,ma1*ma2*ma3)<<endl;
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值