• Maximum Product of Three Numbers 三个数字的最大乘积


    /**

    参考:
      https://www.cnblogs.com/grandyang/p/7084957.html
    * @brief The Solution class * Given an integer array, find three numbers whose product is maximum and output the maximum product. Example 1: Input: [1,2,3] Output: 6 Example 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.
    */ class Solution{ public: int maximumProduct(vector<int>& nums){ int n = nums.size(); sort(nums.begin(),nums.end()); int p = nums[0]*nums[1]*nums[n-1]; return max(p,nums[n-1]*nums[n-2]*nums[n-3]); } }; class Solution{ public: int maximumProduct(vector<int> &nums){ int mx1 = INT_MIN,mx2 = INT_MIN,mx3 = INT_MIN; int mn1 = INT_MAX,mn2 = INT_MAX; for(int num : nums){ //求最大的三个数的方式 if(num > mx1){ mx3 = mx2;mx2 = mx1;mx1 = num; } else if(num>mx2){ mx3 = mx2;mx2 = num; } else if(num > mx3){ mx3 = num; } //求最小的两个数的方式 if(num < mn1){ mn2 = mn1;mn1 = num; } else if(num < mn2){ mn2 = num; } } return max(mx1*mx2*mx3,mx1*mn1*mn2); } };
    怕什么真理无穷,进一寸有一寸的欢喜。---胡适
  • 相关阅读:
    springmvc乱码问题
    51nod 还是01串
    51nod 1276 岛屿的数量
    poj 2486 a apple tree
    hdu 1011 Starship Troopers
    poj 1155 TELE
    hdu 4586 Play the Dice
    hdu 5023 A Corrupt Mayor's Performance Art(线段树水题)
    Appleman and Tree
    hdu 4003
  • 原文地址:https://www.cnblogs.com/hujianglang/p/12468963.html
Copyright © 2020-2023  润新知