zoukankan      html  css  js  c++  java
  • 628. Maximum Product of Three Numbers

    问题:求一个数列里三个数相乘的最大值

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

    方针:

    最大乘积 =

    最大的3个数相乘

    or

    最小的两个数(两个负数)*最大的数

    代码参考:

     1 class Solution {
     2 public:
     3     int maximumProduct(vector<int>& nums) {
     4         vector<int> max3v(3, INT_MIN);
     5         vector<int> min2v(2, INT_MAX);
     6         for(int i:nums){
     7             if(i>max3v[0]){
     8                 max3v[2] = max3v[1];
     9                 max3v[1] = max3v[0];
    10                 max3v[0] = i;
    11             }else if(i>max3v[1]){
    12                 max3v[2] = max3v[1];
    13                 max3v[1] = i;
    14             }else if(i>max3v[2]){
    15                 max3v[2] = i;
    16             }
    17             if(i<min2v[0]){
    18                 min2v[1] = min2v[0];
    19                 min2v[0] = i;
    20             }else if(i<min2v[1]){
    21                 min2v[1] = i;
    22             }
    23         }
    24         return max(max3v[0]*max3v[1]*max3v[2],max3v[0]*min2v[0]*min2v[1]);
    25     }
    26 };
  • 相关阅读:
    [转]进程间通信----pipe和fifo
    [转]udev
    [转]netlink
    [转]进程间通信-----管道
    [转]socket
    [转]armv8 memory system
    [转]内核态和用户态
    [转]dpdk内存管理
    meeting and robert rules
    notion
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/12496803.html
Copyright © 2011-2022 走看看