find a maximum product triplet in this array
O(N)扫一遍array就可以了: 找三个最大的, 两个最小的,然后根据第三个最大的正负来判断。
Approach 4: O(n) Time, O(1) Space
- Scan the array and compute Maximum, second maximum and third maximum element present in the array.
- Scan the array and compute Minimum and second minimum element present in the array.
- Return the maximum of product of Maximum, second maximum and third maximum and product of Minimum, second minimum and Maximum element.
Note – Step 1 and Step 2 can be done in single traversal of the array.
int maxProduct(int arr[], int n) { // if size is less than 3, no triplet exists if (n < 3) return -1; // Initialize Maximum, second maximum and third // maximum element int maxA = INT_MIN, maxB = INT_MIN, maxC = INT_MIN; // Initialize Minimum and second mimimum element int minA = INT_MAX, minB = INT_MAX; for (int i = 0; i < n; i++) { // Update Maximum, second maximum and third // maximum element if (arr[i] > maxA) { maxC = maxB; maxB = maxA; maxA = arr[i]; } // Update second maximum and third maximum element else if (arr[i] > maxB) { maxC = maxB; maxB = arr[i]; } // Update third maximum element else if (arr[i] > maxC) maxC = arr[i]; // Update Minimum and second mimimum element if (arr[i] < minA) { minB = minA; minA = arr[i]; } // Update second mimimum element else if(arr[i] < minB) minB = arr[i]; } return max(minA * minB * maxA, maxA * maxB * maxC); }