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.
理很明白,逻辑没弄清.
想法是:找出 top3 最大, top2 最小, 一趟找出, 关键是逻辑.
形象一些讲就是: 孩子们长身体,老大穿不了的衣服传给老二,老二穿不了的传给老三,老三找到合适衣服直接穿上.
人家逻辑:
\(O(n)\) time, \(O(1)\) extra space.
int maximumProduct(vector<int>& A) {
int m1 = INT_MIN, m2 = INT_MIN;
int m3 = INT_MIN, s1 = INT_MAX, s2 = INT_MAX, res, i, v;
//孩子们长身体,老大穿不了的衣服传给老二,老二穿不了的传给老三.
for (i = 0; i < A.size(); i++) {
v = A[i];
if (v > m1) {m3 = m2; m2 = m1; m1 = v;}
else if (v > m2) {m3 = m2; m2 = v;}
else if (v > m3) {m3 = v;}
if (v < s1) {s2 = s1; s1 = v;}
else if (v < s2) {s2 = v;}
}
res = m1 * m2 * m3 > m1 * s1 * s2 ? m1 * m2 * m3 : m1 * s1 * s2;
return res;
}