628. Maximum Product of Three Numbers

xiaoxiao2021-02-28  105

第一次刷leetcode是超级简单的一道题 

一开始还以为是需要用到动态规划。。。

题目如下:Given an integer array, find three numbers whose product is maximum and output the maximum product.

Example 1:Input: [1,2,3]Output: 6Example 2:Input: [1,2,3,4]Output: 24

Note:The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer.

我写的:

//

//  main.c

//  Max product of 3 numbers

//

//  Created by Chiu Chi Kwan on 2017/7/10.

//  Copyright © 2017 ChiuChiuKwan. All rights reserved.

//

#include <stdio.h>

int main(int argc,constchar * argv[])

{

    int n;

    scanf("%d",&n);

    int num[n];

    for(int i=0;i<n;i++)

    {scanf("%d",&num[i]);}

    

    long  result=0;

    long x[n];

    

    for (int t=n-1; t>-1; t--)

    {

        if (t>1)

        {

            x[t]=num[t]*num[t-1]*num[t-2];

            if(x[t]>result)

                result=x[t];

        }

        

        else x[t]=num[t];

    }

    printf("%ld",result);

    

    return0;

}

答案写的:

class Solution { public:     int maximumProduct(vector<int>& nums)      {     sort(nums.begin(), nums.end());     int n = nums.size();     int temp1 = nums[n-1]*nums[n-2]*nums[n-3];     int temp2 = nums[0]*nums[1]*nums[n-1];     return temp1>temp2?temp1:temp2;     } };

还是c艹比较6 我不明白为什么我在leetcode上面运行总是结果为0,还请大神们指导一下,当然通过对比我发现自己忽略了一个环状问题。。。

更新 我知道了:1.它的输入还是加入了【】的。。。2.其实应该是随便选3个最大的 而不是非要连续。。。

转载请注明原文地址: https://www.6miu.com/read-39298.html

最新回复(0)