排序

class Solution {
public:
    /**
     * 最大乘积
     * @param A int整型一维数组 
     * @param ALen int A数组长度
     * @return long长整型
     */
    long long solve(int* A, int n) {
        // write code here
        sort(A, A + n);
        return max((long long) A[0] * A[1] * A[n - 1], (long long)A[n - 3] * A[n - 2] * A[n - 1]);
    }
};

一次遍历

class Solution {
public:
    /**
     * 最大乘积
     * @param A int整型一维数组 
     * @param ALen int A数组长度
     * @return long长整型
     */
    long long solve(int* A, int n) {
        // write code here
        long long min1 = INT_MAX, min2 = INT_MAX;
        long long max1 = INT_MIN, max2 = INT_MIN, max3 = INT_MIN;
        for(int i = 0; i < n; i ++){
            int x = A[i];
            if(x < min1){
                min2 = min1;
                min1 = x;
            }else if(x < min2){
                min2 = x;
            }

            if(x > max1){
                max3 = max2;
                max2 = max1;
                max1 = x;
            }else if(x > max2){
                max3 = max2;
                max2 = x;
            }else if(x > max3){
                max3 = x;
            }
        }
        return max(min1 * min2 * max1, max1 * max2 * max3);
    }
};