Maximum Product of Two Elements in an Array — LeetCode 1464 Python Solution

EasyArraySortingHeap (Priority Queue)
Problem
#1464
Reading time
2 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(n) auxiliary

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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview