这道题十分不容易啊,做到半夜。
class Solution { public: static int cmp628(int a, int b) { return a > b; } static int cmp628_2(int a, int b) { return abs(a) < abs(b); } int maximumProduct(vector<int>& nums) { const int N = 10000; int Pos[N]; int Nag[N]; int Nor[N]; int i = 0, j = 0, k = 0; for (auto n : nums) { if (n >= 0) { Pos[i] = n; i++; } else { Nag[j] = n; j++; } Nor[k] = n; k++; } sort(Pos, Pos + i, cmp628); sort(Nag, Nag + j); sort(Nor, Nor + k, cmp628_2); int a = INT_MIN, b = INT_MIN, c = INT_MIN, d = INT_MIN, max = INT_MIN; //三正 if (i >= 3) { a = Pos[0] * Pos[1] * Pos[2]; if (j >= 2) { b = Pos[0] * Nag[0] * Nag[1]; } } else if (i >= 2) { a = Pos[0] * Pos[1] * Nag[0]; if (j >= 2) { b = Pos[0] * Nag[0] * Nag[1]; } } if (j >= 3) { c = Nag[0] * Nag[1] * Nag[2]; if (i >= 2) { d = Nag[j - 1] * Pos[0] * Pos[1]; } else if (i == 1) { d = Nag[0] * Nag[1] * Pos[0]; } } else if (j >= 2) { c = Nag[0] * Nag[1] * Pos[0]; if (i >= 2) { d = Nag[j - 1] * Pos[0] * Pos[1]; } else if (i == 1) { d = Nag[0] * Nag[1] * Pos[0]; } } if (max < a) max = a; if (max < b) max = b; if (max < c) max = c; if (max < d) max = d; return max; } };