Python 1913.py
class Solution:
def maxProductDifference(self, nums: List[int]) -> int:
nums.sort()
return nums[-1] * nums[-2] - nums[0] * nums[1]
Difficulty
and has an acceptance rate of about 83% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- 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 provided implementation defines a class Solution with a single method maxProductDifference. The method receives a list of integers, sorts the list in place, and then computes the difference between the product of the two largest numbers and the product of the two smallest numbers. The result is returned as an integer.
Key Steps
The algorithm proceeds through three distinct operations:
The first operation sorts the input list:
nums.sort()
Sorting arranges the elements in non-decreasing order, guaranteeing that the smallest values occupy the first positions and the largest values occupy the last positions.
The second operation extracts the two largest elements using negative indexing:
largest_product = nums[-1] * nums[-2]
Negative indices refer to elements counted from the end of the list, so nums[-1] is the maximum value and nums[-2] is the second-maximum value after sorting.
The third operation extracts the two smallest elements using standard forward indexing:
smallest_product = nums[0] * nums[1]
Index 0 points to the minimum value and index 1 points to the second-minimum value.
Finally, the method returns the difference between the two products:
return largest_product - smallest_product
Edge Cases
Because the list is sorted before any arithmetic is performed, the method correctly handles several edge conditions:
When the list contains duplicate values, sorting preserves their relative order, and the same value may appear in both the largest and smallest positions. The multiplication steps still produce valid products, and the subtraction yields the correct difference.
If the list includes negative numbers, sorting places the most negative values at the beginning and the most positive values at the end. The product of two negative numbers becomes positive, and the algorithm naturally accounts for this when computing largest_product and smallest_product. The subtraction therefore reflects the true product difference even when sign changes are involved.
When the list length is exactly four, which is the minimal size required to have two distinct smallest and two distinct largest elements, the algorithm still functions correctly because the indices 0, 1, -2, and -1 are all valid. The method does not rely on any extra elements beyond these four positions.
Performance Optimizations
The implementation leverages the in-place sort method, which avoids allocating an additional list for ordering. By sorting the original list, memory overhead is minimized. The subsequent product calculations use direct indexing without any loops or auxiliary data structures, resulting in constant-time arithmetic after the sort completes. This straightforward approach eliminates the need for multiple passes over the data, keeping the overall execution path concise and efficient.
ELI5 - Simplified Explanation
Imagine a box full of number cards. The goal is to find the biggest ones and the smallest ones. First, the code picks up all the cards and lines them up from the smallest number on the left to the biggest number on the right. Once they are in a nice, neat row, it grabs the two biggest cards from the very end of the line and multiplies them together to see how giant that product is. Then, it grabs the two smallest cards from the beginning of the line and multiplies them together to see how tiny that product is. Finally, it takes the giant number and subtracts the tiny number to see the big difference between them.
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 | Python | C++ | Java | TS | ||||
| WalkCCC | Python | C++ | Java | ||||||
| leetcode.ca | Python | C++ | JS | Java | Go | ||||
| Progiez | Python | C++ | Java | ||||||
| github | black-shadows | C++ | |||||||
| chandansgowda | Python | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JS | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JS | ||||||||
| lkwq007 | Python | ||||||||
| muhammadfarhankt | Go | ||||||||
| pruthvikp | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java | ||||||||
| AlgoMonster | C++, Python, Java, TypeScript | ||||||||
| WalkCCC | C++, Python, Java | ||||||||
| leetcode.ca | C++, Go, Java, JavaScript, Python | ||||||||
| Progiez | C++, Java, Python | ||||||||
| black-shadows | C++, C++ | ||||||||
| chandansgowda | Python | ||||||||
| charles-wangkai | Java | ||||||||
| everthis | JavaScript | ||||||||
| fartem | Ruby | ||||||||
| fsq | C++ | ||||||||
| JoshCrozier | JavaScript | ||||||||
| lkwq007 | Python | ||||||||
| muhammadfarhankt | Go | ||||||||
| pruthvikp | Python | ||||||||
| suxrobGM | C# | ||||||||
| varunu28 | Java |
Videos
Solved On The Same Day
- problem 385: Mini Parser
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