MediumNo. 1874LeetCode Premium

Minimize Product Sum of Two Arrays — LeetCode 1874 Python Solution

Pattern
Greedy
Topics
Greedy, Array, Sorting
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

PythonSolution
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

Time
O(n × log n)
Space · auxiliary
O(log n)

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

Related problems
No.ProblemDifficulty
1877Minimize Maximum Pair Sum in ArrayMedium
0179Largest NumberMedium
0324Wiggle Sort IIMedium
0452Minimum Number of Arrows to Burst BalloonsMedium
0455Assign CookiesEasy
0502IPOHard

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 × 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.

Free to download. Check it runs on your machine, then pick a plan.