#1913
Maximum Product Difference Between Two Pairs
EasyArraySortingSortingArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
To maximize the product difference, we only need the two largest and two smallest numbers from the array. This is because the maximum product will come from the largest numbers and the minimum product from the smallest numbers.
⚙️
Algorithm
4 steps- 1Step 1: Sort the array.
- 2Step 2: Calculate the product of the two largest numbers (last two elements in sorted array).
- 3Step 3: Calculate the product of the two smallest numbers (first two elements in sorted array).
- 4Step 4: Return the difference between the two products.
solution.py5 lines
1# Full working Python code
2
3def maxProductDifference(nums):
4 nums.sort()
5 return (nums[-1] * nums[-2]) - (nums[0] * nums[1])ℹ
Complexity note: The time complexity is O(n log n) due to the sorting step. The space complexity is O(1) since we are only using a constant amount of space for calculations.
- 1The maximum product difference can be achieved by focusing on the largest and smallest numbers.
- 2Sorting the array simplifies the problem by allowing easy access to the required numbers.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.