[codility]Max-product-of-three

// you can also use includes, for example:
#include <algorithm>
#include <climits>
int solution(vector<int> &A) {
    // write your code in C++98
    //...sort A first
    sort(A.begin(), A.end());
    //...enumerate Q, and then divide to 4 cases, keep record of globalMax
    int globalMax = INT_MIN;
    int n = A.size();
    for(int Q = 1; Q < n-1; ++Q)
    {
        int localMax;
        if(A[Q] > 0)
        {
            if(A[Q-1] < 0) localMax = A[Q-1]*A[Q]*A[Q+1];
            else if(A[Q-1] == 0) localMax = 0;
            else localMax = A[Q-1]*A[Q]*A[n-1];
        }
        else if(A[Q] == 0) localMax = 0;
        else//A[Q] < 0
        {
            if(A[n-1] < 0) localMax = A[Q-1]*A[Q]*A[n-1];
            else if(A[n-1] == 0) localMax = 0;
            else localMax = A[0]*A[Q]*A[n-1];
        }
        globalMax = max(globalMax, localMax);
    }
    //...return result
    return globalMax;
}

你可能感兴趣的:([codility]Max-product-of-three)