Python 1464.py
class Solution:
def maxProduct(self, nums: List[int]) -> int:
# let's avoid a full-blown sort
# and do everything from scratch
one = max(nums[0], nums[1]) # largest values
two = min(nums[0], nums[1]) # second largest
for i in range(2, len(nums)):
x = nums[i]
if one <= x: # new largest value
two, one = one, x
elif two < x: # not largest, but new second largest value
two = x
return (one - 1) * (two - 1)
Difficulty
and has an acceptance rate of about 84% (500k+ submissions).
Typical patterns to solve this problem:
- Array
- Heap (Priority Queue)
- Sorting
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The maxProduct method receives a list of integers and returns the maximum value obtainable by selecting two distinct elements, subtracting one from each, and multiplying the results. The implementation deliberately avoids sorting the entire list and instead determines the two largest values in a single traversal. By focusing on the two greatest numbers, the method directly computes the desired product without extra data structures.
Key Steps
The algorithm begins by establishing the initial candidates for the largest and second-largest elements. It compares the first two entries of the input list and assigns the greater one to one and the smaller to two.
one = max(nums[0], nums[1]) # largest value seen so far
two = min(nums[0], nums[1]) # second largest value seen so far
A loop then iterates over the remaining elements, starting at index 2. For each element x, the code evaluates whether x should replace one of the current top candidates.
for i in range(2, len(nums)):
x = nums[i]
if one <= x: # x is at least as large as the current largest
two, one = one, x # shift the previous largest to second place, store x as new largest
elif two < x: # x is smaller than the largest but larger than the second largest
two = x # update the second largest
The conditional one <= x ensures that when x equals the current largest, the algorithm still treats it as a new largest value, moving the previous largest into the second-largest slot. This behavior correctly handles duplicate maximum values, guaranteeing that both positions reflect the two highest numbers even when they are identical.
After processing the entire list, the method computes the final product by subtracting one from each of the two stored values and multiplying them.
return (one - 1) * (two - 1)
Edge Cases Handled
The code gracefully manages several edge conditions without additional checks. When the input list contains exactly two elements, the initial assignment of one and two already represents the final pair, and the loop body is skipped, leading directly to the correct product calculation. In cases where the list includes duplicate maximum values, the one <= x branch captures the duplicate as the new largest, while the previous maximum becomes the second largest, ensuring both slots hold the highest possible numbers. The algorithm also works correctly with negative numbers or zeros because the comparison logic does not assume positivity; it simply tracks the two greatest values according to the standard ordering of integers.
Performance Optimizations
The implementation achieves optimal efficiency by performing a single linear pass over the input array. By maintaining only two scalar variables (one and two), it avoids allocating auxiliary storage such as auxiliary arrays or heaps. The decision to forgo a full sort eliminates the O(n log n) overhead that a conventional sorting approach would incur. The in-place updates of the top two candidates ensure that each element is examined exactly once, resulting in minimal computational work while preserving correctness. This design yields constant additional memory usage and leverages simple integer comparisons, which are among the fastest operations available in typical runtime environments.
ELI5 - Simplified Explanation
Imagine having a big basket full of numbered blocks. The goal is to pick out the two biggest blocks to make the largest possible prize. To do this, look at the first two blocks in the basket and decide which one is the biggest and which one is the second biggest.
Now, walk through the rest of the basket one block at a time. Every time a new block is picked up, compare it to the two biggest ones held so far. If the new block is even bigger than the biggest one, the old biggest block moves down to second place, and the new one takes the top spot. If the new block is not the biggest of all but is still larger than the second one, it takes that second spot instead. Keep doing this until every block in the basket has been checked. Once the final two biggest blocks are found, take each one, subtract one from its number, and multiply those two new, smaller numbers together. That gives the final answer.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||||
| WalkCCC | C++ | Python | Java | |||||||||
| leetcode.ca | C++ | Python | Java | Go | C | PHP | Rust | TS | ||||
| Progiez | C++ | Python | Java | |||||||||
| github | BigEggStudy | C# | ||||||||||
| black-shadows | C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JS | |||||||||||
| fartem | Ruby | |||||||||||
| fsq | C++ | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JS | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| pruthvikp | Python | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| withaarzoo | C++ | |||||||||||
| YuriSpiridonov | Python | |||||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||||
| WalkCCC | C++, Python, Java | |||||||||||
| leetcode.ca | C, C++, Go, Java, PHP, Python, Rust, TypeScript | |||||||||||
| Progiez | C++, Java, Python | |||||||||||
| BigEggStudy | C# | |||||||||||
| black-shadows | C++, C++ | |||||||||||
| chandansgowda | Python | |||||||||||
| charles-wangkai | Java | |||||||||||
| DimitrisJim | C | |||||||||||
| everthis | JavaScript | |||||||||||
| fartem | Ruby | |||||||||||
| fsq | C++ | |||||||||||
| halfrost | Go | |||||||||||
| haoel | C++ | |||||||||||
| JoshCrozier | JavaScript | |||||||||||
| keineahnung2345 | C++ | |||||||||||
| Krazune | C++ | |||||||||||
| lkwq007 | Python | |||||||||||
| pruthvikp | Python | |||||||||||
| suxrobGM | C# | |||||||||||
| trung-hn | Python | |||||||||||
| varunu28 | Java | |||||||||||
| withaarzoo | C++ | |||||||||||
| YuriSpiridonov | Python |
Videos
Solved On The Same Day
- problem 1642: Furthest Building You Can Reach
- problem 1753: Maximum Score From Removing Stones
- problem 1834: Single-Threaded CPU
- problem 1962: Remove Stones to Minimize the Total
- problem 1675: Minimize Deviation in Array
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality