Minimize Product Sum of Two Arrays — LeetCode 1874 Python Solution

MediumLeetCode PremiumGreedyArraySorting
Problem
#1874
Pattern
Greedy
Reading time
2 min

The problem

The product sum of two equal-length arrays a and b is equal to the sum of a[i] * b[i] for all 0 <= i < a.length (0-indexed). For example, if a = [1,2,3,4] and b = [5,2,3,1], the product sum would be 1*5 + 2*2 + 3*3 + 4*1 = 22.

Example

Input
nums1 = [5,3,4,2], nums2 = [4,2,2,5]
Output
40
Explanation
We can rearrange nums1 to become [3,5,4,2]. The product sum of [3,5,4,2] and [4,2,2,5] is 3*4 + 5*2 + 4*2 + 2*5 = 40.

Python solution

Python
class Solution:
    def minProductSum(self, nums1: List[int], nums2: List[int]) -> int:
        nums1.sort()
        nums2.sort(reverse=True)
        return sum(x * y for x, y in zip(nums1, nums2))

Complexity

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

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 1874. Minimize Product Sum of Two Arrays is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1874. Minimize Product Sum of Two Arrays?
LeetCode 1874. Minimize Product Sum of Two Arrays is rated Medium on LeetCode.
What is the time complexity of LeetCode 1874. Minimize Product Sum of Two Arrays?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 1874. Minimize Product Sum of Two Arrays?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 1874. Minimize Product Sum of Two Arrays cover?
LeetCode 1874. Minimize Product Sum of Two Arrays is tagged Greedy, Array and Sorting on LeetCode.
Is LeetCode 1874. Minimize Product Sum of Two Arrays a premium problem?
Yes. LeetCode 1874. Minimize Product Sum of Two Arrays is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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