EasyNo. 1464
Maximum Product of Two Elements in an Array — LeetCode 1464 Python Solution
- Pattern
- Heap / Priority Queue
- Topics
- Array, Sorting, Heap (Priority Queue)
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value of (nums[i]-1)\*(nums[j]-1).
Example
- Input
- nums = [3,4,5,2]
- Output
- 12
- Explanation
- If you choose the indices i=1 and j=2 (indexed from 0), you will get the maximum value, that is, (nums[1]-1)*(nums[2]-1) = (4-1)*(5-1) = 3*4 = 12.
Python solution
class Solution:
def maxProduct(self, nums: List[int]) -> int:
ans = 0
for i, a in enumerate(nums):
for b in nums[i + 1 :]:
ans = max(ans, (a - 1) * (b - 1))
return ansComplexity
- Time
- O(n log n)
- Space · auxiliary
- O(n)
Pattern: Heap / Priority Queue
Keep only the best k elements, or always pull the smallest, in log time. LeetCode 1464. Maximum Product of Two Elements in an Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Heap (Priority Queue).
The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0215 | Kth Largest Element in an Array | Medium |
| 0218 | The Skyline Problem | Hard |
| 0506 | Relative Ranks | Easy |
| 0912 | Sort an Array | Medium |
| 0973 | K Closest Points to Origin | Medium |
| 1094 | Car Pooling | Medium |
Frequently asked questions
- How hard is LeetCode 1464. Maximum Product of Two Elements in an Array?
LeetCode 1464. Maximum Product of Two Elements in an Array is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1464. Maximum Product of Two Elements in an Array?
The Python solution on this page runs in O(n log n).
- What is the space complexity of LeetCode 1464. Maximum Product of Two Elements in an Array?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1464. Maximum Product of Two Elements in an Array cover?
LeetCode 1464. Maximum Product of Two Elements in an Array is tagged Array, Sorting and Heap (Priority Queue) on LeetCode.