Maximum Product of Three Numbers β π‘ Intermediate (2/3) β LeetCode Daily Python Solution (the two-negatives trap)
π Jump to your level: π‘ Intermediate: 0:16β3:25 π Full written solution: https://interview-kit-fe.vercel.app/maximum-product-of-three-numbers-intermediate π» Code on GitHub: https://github.com/timepasshub2539-hue/leetcode-python/tree/main/maximum-product-of-three-numbers-intermediate Chapters: 0:00 The Problem: Maximum Product of Three Numbers 0:16 π‘ Intermediate: Two negatives just stole your answer 0:28 One word breaks the obvious answer 0:42 What we're actually asked 0:56 The obvious idea first 1:05 ...until this one input 1:16 The tools we need 1:27 The pattern: Two Corners 1:39 The solution, part one 1:52 The solution, part two 2:02 Pause: what does this return? 2:12 The reveal 2:21 Alternative: skip the sort 2:36 Which one should you pick? 2:48 Edge cases that break people 3:06 You've got the Two Corners trick The obvious answer to Maximum Product of Three Numbers is a trap β two negatives can quietly beat your three biggest numbers. In this LeetCode daily walkthrough we build the intuition step by step, meet the Two Corners pattern, and code a clean Python solution. Then we skip the sort entirely for an O(n) version and compare which to reach for in an interview. Ends with the edge cases that break most people. #LeetCode #Python #CodingInterview #DSA #TwoCorners Watch next: - Maximum Product of Two Digits β π‘ Intermediate (2/3) β LeetCode Daily Python Solution (swap one digit, +60): https://youtu.be/09Y3a6y89q0 - The Problem: Maximum Product of Two Digits #shorts: https://youtu.be/QfCuvgvEKT8 - Maximum Product of Two Digits β π’ Beginner (1/3) β LeetCode Daily Python Solution (the trick nobody sees): https://youtu.be/LcqYDC9_CSI
SEO PACKAGE
1. SEO Title
Maximum Product of Three Numbers in Python β The Two-Negatives Trap Every Coder Falls For (LeetCode 628)
2. SEO Subtitle
Learn why the three biggest numbers don't always win, and how the Two Corners pattern gives you a clean, correct Python solution in five lines.
3. Featured Quote
"Size isn't the same as product once negatives enter the room. The answer always hides at the corners of a sorted array."
4. Meta Description
Solve LeetCode 628 Maximum Product of Three Numbers in Python. Master the two-negatives trap, the Two Corners pattern, sorting vs O(n), and every edge case.
5. URL Slug
maximum-product-of-three-numbers-python-two-corners
6. Keywords
Maximum Product of Three Numbers, LeetCode 628, Python coding interview, two negatives trap, Two Corners pattern, array algorithms, sorting interview problem, O(n) array scan, product of three numbers, negative numbers algorithm, data structures Python, coding interview preparation, algorithm intuition, edge cases interview, greedy array problem, Python list sort, time complexity analysis, LeetCode daily challenge, software engineering interview, beginner algorithms
7. Tags
python, leetcode, coding-interview, algorithms, data-structures, arrays, sorting, problem-solving, dsa, interview-preparation, two-corners, greedy, time-complexity
8. Introduction
Some coding problems are hard because the algorithm is complex. Maximum Product of Three Numbers is hard for the opposite reason β it looks trivial, and that is exactly the trap.
Ask any developer for the answer and you'll hear the same instant reply: "Sort the array, take the three biggest, multiply them." It sounds airtight. It feels done. And for a list of all-positive numbers, it's even correct. That confidence is the problem, because a single negative-heavy input turns the obvious rule inside out.
Interviewers love this question precisely because it separates people who pattern-match to keywords from people who reason about the actual math. The word "largest" pulls your brain toward the biggest values, and you skip right past the fact that two large negative numbers multiply into a large positive one. The interviewer isn't testing whether you can call sort(). They're testing whether you notice the case that breaks your first answer β and whether you handle it cleanly instead of bolting on messy special cases.
This is a foundational skill for every coding interview: recognizing that "biggest input" and "biggest result" are not the same claim. Get comfortable with it here on an approachable LeetCode problem, and you'll carry the instinct into far harder algorithms and data structures questions where the same corner-case reasoning shows up in disguise.
9. Problem Overview
You're given a list of integers. Your task is to choose exactly three of them whose product is as large as possible, then return that product.
The values can be positive, negative, or zero. You must pick three distinct positions in the array (you can't reuse the same element twice), and the list is guaranteed to contain at least three numbers.
That's the entire specification. No sorting is required by the problem, no ordering of the output β just a single integer: the maximum product achievable by any group of three elements.
The subtlety lives entirely in one word: integers. If the problem promised only positive numbers, this would be a warm-up. Because negatives are allowed, the "obvious" answer is only sometimes right, and your job is to find the approach that is always right.
10. Example
Let's ground the problem in concrete inputs.
Example 1 β all positive
Input: [1, 2, 3, 4]
Output: 24
The three largest values are 2, 3, 4, and 2 Γ 3 Γ 4 = 24. Here the intuitive answer is correct. Nothing negative exists to upset it.
Example 2 β the trap
Input: [-9, -8, 1, 2, 3]
Output: 216
The "three biggest" are 1, 2, 3, giving 6. But look at the corners: -9 Γ -8 = 72, and 72 Γ 3 = 216. Two negatives cancelled their signs and produced a huge positive. The smallest numbers just beat the biggest ones.
Example 3 β all negative
Input: [-1, -2, -3]
Output: -6
Every product is negative here, so we want the one closest to zero. The three largest values (-1, -2, -3) give -6, which is the best available. This is the case that quietly breaks naive solutions that only guard against negatives by pairing them β more on that below.
11. Intuition
Let's discover the solution the way an experienced engineer actually does β by breaking our own first guess.
The starting instinct is honest: the three largest numbers. Multiply them, done. So write that down as Candidate A. It's clearly right when everything is positive, because bigger factors make a bigger product.
Now stress-test it. What kind of input could beat "the three biggest"? The only thing that changes the rules is a negative number, because a negative flips the sign of a product. One negative in your trio makes the whole product negative β bad. But two negatives multiply back into a positive. And if those two negatives are large in magnitude (say -9 and -8), their product (72) can dwarf anything the positive side offers.
So there's a second way to build a large product: take the two most-negative numbers and multiply them by the single largest number. Call that Candidate B. The two negatives give a big positive, and the largest positive scales it up further.
Here's the key insight that ties it together. If you sort the array, both candidates live at predictable, opposite ends:
- The three largest values sit at the right end (Candidate A).
- The two smallest β your potential negative pair β sit at the left end, and the single largest is still on the right (Candidate B).
The answer is always one of these two. This is the pattern worth naming: Two Corners. After sorting, you never need to search the middle. You only ever compare two products and return the bigger one. That's the whole algorithm.
Why only two candidates and not more? Because a maximum product of three needs either zero negatives (three positives β the top three) or exactly two negatives (two negatives + one positive β the biggest positive). Any trio with one or three negatives has a negative sign and can't be the maximum unless everything is negative β and even that case is covered, because when all numbers are negative, the "three largest" are the three closest to zero, which correctly yields the least-negative product.
12. Brute Force Solution
Idea: If the answer is "some three elements," just try every combination of three elements and keep the largest product.
Algorithm:
- Generate all possible triples of indices
(i, j, k). - Compute the product for each triple.
- Track and return the maximum.
from itertools import combinations
def maximum_product_brute(nums):
best = float("-inf")
for a, b, c in combinations(nums, 3):
best = max(best, a * b * c)
return best
Advantages:
- Impossible to get wrong logically β it literally checks everything.
- No clever insight required; great as a sanity check against a smarter solution.
Disadvantages:
- Cubic blow-up. For an array of size
n, there are roughlynΒ³/6triples. - Completely impractical for large inputs β thousands of elements make it crawl.
Time complexity: O(nΒ³) β three nested choices over the array.
Space complexity: O(1) if you iterate lazily with combinations (it yields one triple at a time).
The brute force is useful for understanding and verifying, never for shipping.
13. Optimal Solution
We only ever need to compare two candidates, so we don't need to look at every triple. Sort once, then read the corners.
After sorting ascending:
| Position | nums[0] |
nums[1] |
... | nums[-3] |
nums[-2] |
nums[-1] |
|---|---|---|---|---|---|---|
| Role | smallest | 2nd smallest | ... | 3rd largest | 2nd largest | largest |
- Candidate A (three largest):
nums[-1] * nums[-2] * nums[-3] - Candidate B (two smallest Γ largest):
nums[0] * nums[1] * nums[-1]
Return max(A, B).
Let's trace the pattern on [-9, -8, 1, 2, 3] after sorting (already sorted):
[-9, -8, 1, 2, 3]
β β β
two smallest largest β Candidate B: -9 Γ -8 Γ 3 = 216
[-9, -8, 1, 2, 3]
β β β
three largest β Candidate A: 1 Γ 2 Γ 3 = 6
max(216, 6) = 216 β
Two products, one comparison. That's the optimal use of sorting.
14. Python Code
from typing import List
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
nums.sort()
# Candidate A: the three largest values (right corner).
top_three = nums[-1] * nums[-2] * nums[-3]
# Candidate B: the two smallest (possibly negative) times the largest.
two_neg_one_pos = nums[0] * nums[1] * nums[-1]
return max(top_three, two_neg_one_pos)
If you want the sort-free, linear-time version:
from typing import List
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
max1 = max2 = max3 = float("-inf") # three largest
min1 = min2 = float("inf") # two smallest
for n in nums:
# Update the three largest.
if n > max1:
max1, max2, max3 = n, max1, max2
elif n > max2:
max2, max3 = n, max2
elif n > max3:
max3 = n
# Update the two smallest.
if n < min1:
min1, min2 = n, min1
elif n < min2:
min2 = n
return max(max1 * max2 * max3, min1 * min2 * max1)
15. Code Walkthrough
Sorting version:
nums.sort()β sorts in place, ascending. This forces the largest values to the right end and the smallest (including any negatives) to the left end, so both candidates land at fixed, predictable positions.nums[-1] * nums[-2] * nums[-3]β the three rightmost elements, i.e. the three largest. This is Candidate A.nums[0] * nums[1] * nums[-1]β the two leftmost (smallest) times the single largest. This is Candidate B, the one that catches the two-negatives case.max(...)β Python's built-in comparison hands back whichever candidate is larger. No branching, no special cases.
Linear version:
- We track five running values: the three largest (
max1 β₯ max2 β₯ max3) and the two smallest (min1 β€ min2). - For each number, the
if/elifcascade slots it into the correct rank if it beats the current holder, shifting the others down. The ordering of assignments matters β we updatemax1first so its old value can flow intomax2. - After one pass, we form the same two candidates as before and return the larger.
The linear version does exactly what sorting does, but only keeps the five numbers it actually needs.
16. Dry Run
Let's fully trace the sorting solution on the challenge input from the video: [-5, -4, 1, 2, 3].
Step 1 β sort:
[-5, -4, 1, 2, 3] (already ascending)
Step 2 β Candidate A (three largest):
nums[-1] * nums[-2] * nums[-3] = 3 * 2 * 1 = 6
Step 3 β Candidate B (two smallest Γ largest):
nums[0] * nums[1] * nums[-1] = (-5) * (-4) * 3 = 20 * 3 = 60
Step 4 β compare:
max(6, 60) = 60
Output: 60. The two-negatives corner wins, exactly as the pattern predicts. If we had only checked the top three, we'd have returned 6 and been wrong.
17. Complexity Analysis
Sorting solution
- Time:
O(n log n)β dominated entirely by the sort. Reading five elements and doing a handful of multiplications isO(1). - Space:
O(1)extra if you accept an in-place sort (CPython's Timsort usesO(n)in the worst case internally, but no extra data structure is built by your code).
Linear solution
- Time:
O(n)β a single pass, constant work per element. - Space:
O(1)β just five tracking variables, regardless of input size.
Why these are correct: the sorting version's cost is bounded by the sort because everything after it is fixed constant work. The linear version touches each element once and stores a fixed set of five numbers, so both time and space scale as described.
Honest take: for the input sizes this problem uses, the O(n) scan's speed advantage is mostly theoretical. The sorted version is five lines you can't misread, and readability wins in an interview. Mention the O(n) version, code it if asked, but don't reach for it by default.
18. Alternative Solutions
The linear scan shown above is the main alternative, and the comparison is a great interview talking point:
| Approach | Time | Space | Readability | When to use |
|---|---|---|---|---|
| Sort + two corners | O(n log n) |
O(1) |
Very high | Default choice; small inputs |
| Single-pass scan | O(n) |
O(1) |
Moderate | Large inputs, or when interviewer asks to beat O(n log n) |
The trade-off is honest: the scan is asymptotically faster but juggles more variables, and one wrong elif ordering silently breaks it. The sort is bulletproof and self-documenting. In interviews, lead with the sort, then say, "If you want O(n), I can track the top three and bottom two in a single pass" β that sentence alone signals you understand the trade-off.
19. Edge Cases
- Exactly three elements:
[a, b, c]β both candidates reduce to the same single product. Handled naturally. - All negative:
[-1, -2, -3]β Candidate A (the three closest to zero) gives-6, the least-negative and therefore maximum product.maxpicks it correctly. This is the case that famously breaks solutions checking only the "top three" logic that assumes positivity β here it works because we also consider it as a corner. - Mix with zeros:
[-4, -3, 0, 2]β Candidate B:(-4)(-3)(2) = 24beats Candidate A:(0)(2)(-3) = 0. Zeros are handled with no special code. - Two large negatives dominate:
[-100, -99, 1, 2, 3]β Candidate B:9900 Γ 3 = 29700crushes Candidate A's6. - Large / extreme values: Python integers are arbitrary-precision, so products of very large numbers never overflow. In languages with fixed-width integers, this is where you'd guard against overflow β worth mentioning to your interviewer.
- Duplicates:
[3, 3, 3, 3]β the corners still work; duplicate values are just ordinary elements.
20. Common Mistakes
- Checking only the three largest. The single most common failure. It passes the all-positive tests, then dies on
[-9, -8, 1, 2, 3]and on all-negative inputs. - Pairing negatives without also considering the all-positive case. Some people flip too far and only compute
nums[0] * nums[1] * nums[-1], which fails when there are no useful negatives (e.g.[1, 2, 3, 4]β they'd return1Γ2Γ4 = 8instead of24). You need both candidates and themax. - Forgetting to sort. Reading
nums[0]andnums[-1]only means "smallest" and "largest" after sorting. Skip the sort and you're reading arbitrary positions. - Wrong assignment order in the linear version. Writing
max2 = nbeforemax1 = nloses the oldmax1. The updates must cascade top-down. - Assuming a "smallest three" candidate matters. The two smallest matter (as a negative pair), but the three smallest never do β three negatives give a negative product. Adding that candidate is harmless but reveals a shaky grasp of why only two corners exist.
- Worrying about overflow in Python. Python won't overflow, so guarding against it here is wasted code β though naming the concern for other languages is a plus.
21. Interview Questions
Expect follow-ups like these:
- "Can you do it without sorting?" β Yes: the single-pass scan tracking three max and two min values,
O(n)time,O(1)space. - "Why exactly two candidates? Prove it." β A maximum product of three needs an even count of negatives (0 or 2) to stay positive; those map to "three largest" and "two smallest Γ largest."
- "What changes for the maximum product of k numbers?" β The corner idea generalizes but the case analysis grows: you compare pairing the smallest negatives (in even counts) against the largest positives. It becomes a more careful DP or greedy selection.
- "How would you handle integer overflow in Java or C++?" β Use a 64-bit
longfor the product, or reason about value bounds; Python sidesteps this entirely. - "What if you needed the actual three indices, not just the product?" β Track which elements formed the winning candidate during the scan.
22. Similar Problems
- LeetCode 152 β Maximum Product Subarray. Same two-negatives insight, applied to contiguous subarrays. You track both a running max and a running min because a negative can flip them. This is literally "tomorrow's harder corner problem."
- LeetCode 628 β Maximum Product of Three Numbers. (This problem.)
- LeetCode 1913 β Maximum Product Difference Between Two Pairs. Also solved by looking at the sorted corners (two largest, two smallest).
- LeetCode 414 β Third Maximum Number. Reinforces tracking the top-k values in a single pass, exactly like the linear version here.
- LeetCode 53 β Maximum Subarray. Different operation (sum, not product) but the same "scan once, track a running best" muscle.
They're related because they all reward the habit of reasoning about sign and magnitude at the extremes instead of naively grabbing the biggest values.
23. Key Takeaways
- "Largest input" β "largest product." Negatives break that assumption, and spotting it fast is the real skill.
- Two Corners pattern: after sorting, the answer is either the three rightmost values or the two leftmost times the single rightmost. Compare two, return the max.
- Even count of negatives is what keeps a product positive β that's why only two candidates exist.
- Sort for clarity, scan for speed. Both are
O(1)space; pick the sort unless the interviewer pushes forO(n). - All-negative and zero inputs fall out of the two-candidate
maxfor free β no special cases needed.
24. Watch the Video
Reading builds understanding, but watching the trap spring in real time is what makes it stick. In the video I walk through the two-negatives moment live, build the Two Corners pattern from scratch, and pause for a challenge so you can test yourself before the reveal.
βΆοΈ Watch the full walkthrough here: {LINK}
25. About the Series
This is part of Fun with Learning Technology β a daily series where we take one LeetCode problem and turn it into real, durable intuition. No memorizing solutions, no hand-waving. Every episode builds the why first: how an experienced engineer actually stumbles onto the pattern, where the naive answer breaks, and how to code it cleanly in Python. Whether you're prepping for a coding interview or just sharpening your grasp of algorithms and data structures, there's a fresh problem every day.
26. Call To Action
If this helped the two-negatives trap finally click:
- π Like the video on YouTube β it genuinely helps the channel reach more developers.
- π Subscribe so you catch tomorrow's problem, where this same corner trick cracks a much harder subarray challenge.
- π¬ Subscribe on Substack to get each written breakdown in your inbox.
- π¬ Comment with your answer to the challenge input β did you spot the corner before the reveal?
- π Share this with someone who's grinding LeetCode. The two-negatives trap catches everyone once.
SOCIAL MEDIA
LinkedIn Post
Here's a coding interview question that quietly humbles strong engineers: find the maximum product of three numbers in an array.
Almost everyone answers instantly β "sort it, multiply the three biggest." And for all-positive inputs, that's correct. It feels done.
Then the interviewer slides in [-9, -8, 1, 2, 3].
Top three? 1 Γ 2 Γ 3 = 6.
But -9 Γ -8 Γ 3 = 216.
Two large negatives cancelled their signs into a huge positive, and the smallest numbers just beat the biggest. The word "largest" pulled our brains toward magnitude, and we skipped right past the sign.
The clean fix is a pattern I call Two Corners. After sorting, the answer always lives at the extremes:
β’ the three largest values (right corner), OR β’ the two smallest values Γ the single largest (left corner + right)
You compare exactly two candidates and return the max. Five lines, O(n log n), and it survives the all-negative case for free.
def maximumProduct(nums):
nums.sort()
return max(nums[-1]*nums[-2]*nums[-3],
nums[0]*nums[1]*nums[-1])
The real lesson isn't this one problem. It's the habit: "biggest input" and "biggest result" are not the same claim. The engineers who reason about sign and magnitude at the extremes β instead of pattern-matching to the word "largest" β are the ones who catch the case that breaks their first answer.
That instinct shows up everywhere in algorithms and data structures. This problem is just where it's cheapest to learn.
What other "obvious" problems have a trap like this? π
#Python #LeetCode #CodingInterview #Algorithms #SoftwareEngineering
Twitter/X Thread
1/ "Find the max product of three numbers in an array."
Sounds trivial. Sort, take the top 3, multiply.
That answer is a trap β and it's how this problem quietly beats strong engineers. π§΅
2/ The gut instinct: sort β three biggest β multiply.
For [1, 2, 3, 4] that gives 2Γ3Γ4 = 24. Correct.
For all-positive inputs, you're done. That's the dangerous part β it feels finished.
3/
Now try [-9, -8, 1, 2, 3].
Top three: 1 Γ 2 Γ 3 = 6.
But: -9 Γ -8 Γ 3 = 216.
The two SMALLEST numbers just crushed the three biggest.
4/ Why? Two negatives multiply into a positive.
And if those negatives are large in magnitude, their product is huge. Size and product stop meaning the same thing the moment negatives enter.
5/ So there are really only two ways to build the max product of three:
A) three largest numbers B) two smallest (negative) Γ the single largest
The answer is always one of these.
6/ Sort the array and both candidates sit at the ends:
A = last three (right corner) B = first two Γ last one (left + right)
I call it the Two Corners pattern. You never check the middle.
7/
def maximumProduct(nums):
nums.sort()
return max(nums[-1]*nums[-2]*nums[-3],
nums[0]*nums[1]*nums[-1])
Five lines. O(n log n). Compare two candidates, return the max.
8/ Bonus: it handles all-negatives for free.
[-1, -2, -3] β candidate A gives -6, the least-negative (best) product. max picks it correctly. No special case needed.
9/
Want O(n)? Skip the sort, track the 3 largest + 2 smallest in one pass.
Technically faster. But more variables to juggle, easy to get an elif wrong. For interview-sized inputs, just sort.
10/ The real takeaway isn't this problem.
It's the habit: "biggest input" β "biggest result." Reason about sign and magnitude at the extremes.
That instinct cracks much harder array problems too. Full walkthrough π
Facebook Post
Ever been this confident about a coding answer... right before it falls apart? π
Here's a classic: find three numbers in a list with the biggest possible product. Easy, right? Sort them, grab the three biggest, multiply. Done.
Then someone hands you [-9, -8, 1, 2, 3].
The three biggest give you 6. But -9 Γ -8 Γ 3 = 216! Two negatives multiply into a big positive, and suddenly the smallest numbers win.
The clean trick: after sorting, the answer is always at the "corners" β either the three biggest, or the two smallest times the single biggest. Check both, take the winner. Five lines of Python and it even handles all-negative lists automatically.
I break the whole thing down step by step in today's video β including the challenge where you get to catch the trap yourself before I reveal it. Come learn something new today! π₯π
Reddit Summary
The two-negatives trap in "Maximum Product of Three Numbers" (LeetCode 628)
Sharing a walkthrough of a deceptively simple array problem, since the reasoning is more useful than the code.
The task: pick three integers from a list with the maximum product. The instinctive answer β sort and multiply the three largest β is correct only for all-positive inputs. It fails on things like [-9, -8, 1, 2, 3], where -9 Γ -8 Γ 3 = 216 beats the top three's 6. Two large negatives multiply into a large positive.
The generalization: a max product of three needs an even number of negatives (0 or 2) to stay positive. That leaves exactly two candidates after sorting:
nums[-1] * nums[-2] * nums[-3](three largest)nums[0] * nums[1] * nums[-1](two smallest Γ largest)
Return max() of the two. O(n log n) time, O(1) extra space. It also handles all-negative inputs correctly, since the three-largest candidate becomes the least-negative product.
If you want O(n), track the three largest and two smallest values in a single pass β same two candidates, no sort. Faster asymptotically, but more error-prone with the running-min/max updates, and for typical input sizes the gain is negligible.
The transferable idea: reason about sign and magnitude at the extremes of a sorted array rather than grabbing the biggest values. The same instinct shows up in Maximum Product Subarray (152), where you track a running min alongside the max for the same reason.
Happy to discuss the O(n) version or the k-numbers generalization in the comments.
GITHUB README
# Maximum Product of Three Numbers (LeetCode 628) β Python
Given an integer array, find three numbers whose product is maximum and return
that product.
## Problem
You are given a list of integers (positive, negative, or zero). Choose exactly
three elements so their product is as large as possible, and return that product.
The array has at least three elements.
- `[1, 2, 3, 4] β 24` (2 Γ 3 Γ 4)
- `[-9, -8, 1, 2, 3] β 216` (-9 Γ -8 Γ 3)
- `[-1, -2, -3] β -6` (least-negative product)
## Intuition
The obvious answer β "sort and multiply the three largest" β is only correct
when all values are positive. Negatives break it, because **two negatives
multiply into a positive**. Two large-magnitude negatives can outproduce the
three biggest numbers.
A maximum product of three needs an **even count of negatives (0 or 2)** to stay
positive. That leaves exactly two candidates once the array is sorted:
- **Three largest** (right corner)
- **Two smallest Γ the single largest** (left corner + right)
Compare the two, return the larger. This is the **Two Corners** pattern.
## Approach
1. Sort the array ascending.
2. Candidate A = `nums[-1] * nums[-2] * nums[-3]`.
3. Candidate B = `nums[0] * nums[1] * nums[-1]`.
4. Return `max(A, B)`.
The all-negative case is handled for free: Candidate A becomes the
least-negative (maximum) product.
## Python Solution
```python
from typing import List
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
nums.sort()
top_three = nums[-1] * nums[-2] * nums[-3]
two_neg_one_pos = nums[0] * nums[1] * nums[-1]
return max(top_three, two_neg_one_pos)
O(n) variant (no sort)
from typing import List
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
max1 = max2 = max3 = float("-inf")
min1 = min2 = float("inf")
for n in nums:
if n > max1: max1, max2, max3 = n, max1, max2
elif n > max2: max2, max3 = n, max2
elif n > max3: max3 = n
if n < min1: min1, min2 = n, min1
elif n < min2: min2 = n
return max(max1 * max2 * max3, min1 * min2 * max1)
Complexity
| Approach | Time | Space |
|---|---|---|
| Sort + corners | O(n log n) |
O(1) |
| Single-pass | O(n) |
O(1) |
Prefer the sort for readability; use the scan when asked to beat O(n log n).
Video
βΆοΈ Full walkthrough: {LINK}
Article
Full explanation with intuition, dry run, edge cases, and common mistakes is in the accompanying article. Part of the Fun with Learning Technology series. ```
The solution
top3 = nums[-1] * nums[-2] * nums[-3]
low2 = nums[0] * nums[1] * nums[-1]
return max(top3, low2)Ready to try it yourself? Solve General problems with instant feedback in the practice sandbox.
Practice now β


