Given an integer array nums with at least three elements, choose three distinct indices and return the maximum product of their values. Equal values can be used if they occur at different indices.
Example 1
Input nums = [1, 2, 3]
Output 6
Explanation There is only one triplet. Its product is 1 × 2 × 3 = 6.
Example 2
Input nums = [1, 2, 3, 4]
Output 24
Explanation Choosing 2, 3, and 4 gives 2 × 3 × 4 = 24.
Brute Force Approach
The maximum product can come from different combinations of positive and negative numbers. Three positive numbers produce a positive product, but two negative numbers and a positive number can produce an even larger one. For example, in [-10, -9, 1, 2, 3], the triplet [-10, -9, 3] gives 270, while [1, 2, 3] gives 6. Trying every triplet covers both cases.
Choose indices in increasing order, i < j < k, so each triplet uses three different positions and is checked exactly once. For each i, start j at i + 1. For each j, start k at j + 1. Initialise the best product with the product of the first three elements. This gives us a valid starting answer even when every triplet has a negative product.
Approach
Initialise the best product with the product of the first three elements.
Use the first loop to choose index
i, leaving at least two elements after it.Use two more loops to choose
jafteriandkafterj.Multiply the three values using
longarithmetic from the first multiplication. If the product is larger than the best product so far, update it.Return the best product after checking all triplets.
Dry Run
Maximum product of three numbers Brute force
Solution
#include <bits/stdc++.h>using namespace std;class Solution {public: // Find the maximum product by checking every triplet. int maximumProduct(vector<int>& nums) { const int n = nums.size(); // Start with a valid triplet, assuming at least three elements. long long bestProduct = 1LL * nums[0] * nums[1] * nums[2]; // Choose three distinct indices in increasing order. for (int i = 0; i < n - 2; ++i) { for (int j = i + 1; j < n - 1; ++j) { for (int k = j + 1; k < n; ++k) { // Use long long arithmetic for the multiplication. long long product = 1LL * nums[i] * nums[j] * nums[k]; // Keep the largest product found so far. bestProduct = max(bestProduct, product); } } } return bestProduct; }};int main() { Solution solution; vector<int> nums = {1, 2, 3, 4}; cout << solution.maximumProduct(nums) << '\n'; // Prints 24. return 0;}Complexity Analysis
Time Complexity : O(N³), because the algorithm checks every triplet in constant time.
Space Complexity :O(1), because it uses a fixed number of variables.
Better Approach
A large product can come from large positive numbers, but negative numbers can help too. Two negatives multiply to a positive, and the farther both are from zero, the larger their product. In a sorted array, the most negative values are at the beginning. If the first two numbers are negative, they form the negative pair with the largest positive product.
For example, in [-10, -10, 2, 5], the last three elements are -10, 2, and 5, giving -10 × 2 × 5 = -100. The first two elements are both -10, so their product is 100. Pairing them with the largest value, 5, gives 100 × 5 = 500. Since 500 is greater than -100, it is the maximum product.
Sorting gives us two candidate triplets. The last three elements give the best product when all the values are nonnegative. They also handle an all-negative array, where the three values closest to zero give the product closest to zero. When two negatives and a positive can give the best product, the first two elements provide the negative pair and the last element provides the largest positive factor.
Approach
Sort
numsin ascending order and letnbe its length.Multiply
nums[n - 3],nums[n - 2], andnums[n - 1]to get the first candidate.Multiply
nums[0],nums[1], andnums[n - 1]to get the second candidate.Compare the two products and return the larger one.
Dry Run
Maximum product of three numbers Better
Solution
#include <bits/stdc++.h>using namespace std;class Solution {public: // Find the maximum product of three elements using sorting. int maximumProduct(vector<int>& nums) { // Sort in ascending order to access the smallest and largest values. sort(nums.begin(), nums.end()); const int n = nums.size(); // First candidate: the product of the three largest values. // Use long long arithmetic for the multiplication. long long threeLargest = 1LL * nums[n - 3] * nums[n - 2] * nums[n - 1]; // Second candidate: the two smallest values and the largest value. // Two large negative values can multiply to a large positive value. long long twoSmallestAndLargest = 1LL * nums[0] * nums[1] * nums[n - 1]; // Return the larger of the two candidate products. return max(threeLargest, twoSmallestAndLargest); }};int main() { Solution solution; vector<int> nums = {-10, -10, 5, 2}; // The maximum product is -10 * -10 * 5 = 500. cout << solution.maximumProduct(nums) << '\n'; return 0;}Complexity Analysis
Time Complexity : O(N log N), because sorting dominates the two product calculations.
Space Complexity : O(log N), because the typical std::sort implementation uses a logarithmic call stack.
Optimal Approach
The sorted approach uses only five values. We can track them in a single scan. The variables max1, max2, and max3 store the three largest values seen so far in descending order, while min1 and min2 store the two smallest in ascending order.
When a value takes a position among the three largest, shift the displaced values down before overwriting them. For example, if (max1, max2, max3) = (8, 5, 3) and the next value is 10, first copy 5 into max3, then copy 8 into max2, and finally set max1 to 10. The result is (10, 8, 5). If the next value is 6, only max3 changes, giving (10, 8, 6).
Update the two smallest values independently. For example, if (min1, min2) = (-4, -2) and the next value is -10, move -4 into min2 before setting min1 to -10. The result is (-10, -4). A later value of -6 changes only min2, giving (-10, -6).
Approach
Initialise
max1,max2, andmax3toINT_MIN.Initialise
min1andmin2toINT_MAX.Scan the array once. For each value
x, update both groups:Three largest values: If
x > max1, setmax3 = max2, thenmax2 = max1, thenmax1 = x. Otherwise, ifx > max2, setmax3 = max2andmax2 = x. Otherwise, ifx > max3, setmax3 = x.Two smallest values: If
x < min1, setmin2 = min1andmin1 = x. Otherwise, ifx < min2, setmin2 = x.
Compute
max1 × max2 × max3andmin1 × min2 × max1. The second product accounts for the possibility that multiplying two negative values gives a larger positive factor. Return the larger product.
Dry Run
Maximum Product of Three Numbers Optimal
Solution
#include <bits/stdc++.h>using namespace std;class Solution {public: // Find the maximum product by tracking five values in one pass. int maximumProduct(vector<int>& nums) { // Keep the three largest values in descending order. int max1 = INT_MIN, max2 = INT_MIN, max3 = INT_MIN; // Keep the two smallest values in ascending order. int min1 = INT_MAX, min2 = INT_MAX; for (int value : nums) { if (value > max1) { // The new largest pushes the previous two down one position. max3 = max2; max2 = max1; max1 = value; } else if (value > max2) { // The new second largest pushes the previous one to third. max3 = max2; max2 = value; } else if (value > max3) { // Only the third largest needs to change. max3 = value; } // Check the smallest values independently for every element. if (value < min1) { // The previous smallest becomes the second smallest. min2 = min1; min1 = value; } else if (value < min2) { // Only the second smallest needs to change. min2 = value; } } // First candidate: multiply the three largest values. // Use long long arithmetic for the multiplication. long long threeLargest = 1LL * max1 * max2 * max3; // Second candidate: two negatives may give a large positive product. long long twoSmallestAndLargest = 1LL * min1 * min2 * max1; // Return the larger of the two candidate products. return max(threeLargest, twoSmallestAndLargest); }};int main() { Solution solution; vector<int> nums = {-10, -10, 5, 2}; // The maximum product is -10 * -10 * 5 = 500. cout << solution.maximumProduct(nums) << '\n'; return 0;}Complexity Analysis
Time Complexity : O(N), because the algorithm scans the array once and does constant work per element.
Space Complexity : O(1), because it tracks a fixed number of values.
Interview follow-up Questions
Every triplet has a negative product. The three largest values are closest to zero and give the largest product. For [-8, -5, -3, -2], the answer is (-5) × (-3) × (-2) = -30.
Be the first to add a comment.