Minimize Product Sum of Two Arrays - 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.

Given two arrays nums1 and nums2 of length n, return the minimum product sum if you are allowed to rearrange the order of the elements in nums1.

Input & Output

Example 1 — Basic Case
$ Input: nums1 = [5,3,2,4], nums2 = [2,1,4,5]
Output: 35
💡 Note: Sort nums1 ascending [2,3,4,5] and nums2 descending [5,4,2,1]. Product sum: 2×5 + 3×4 + 4×2 + 5×1 = 10 + 12 + 8 + 5 = 35
Example 2 — Minimum Size
$ Input: nums1 = [3,1], nums2 = [2,5]
Output: 11
💡 Note: Sort nums1 [1,3] and nums2 descending [5,2]. Product sum: 1×5 + 3×2 = 5 + 6 = 11
Example 3 — All Same Values
$ Input: nums1 = [2,2,2], nums2 = [3,3,3]
Output: 18
💡 Note: All elements are same, so any arrangement gives: 2×3 + 2×3 + 2×3 = 6 + 6 + 6 = 18

Constraints

  • n == nums1.length == nums2.length
  • 1 ≤ n ≤ 1000
  • -100 ≤ nums1[i], nums2[i] ≤ 100

Visualization

Tap to expand
Minimize Product Sum of Two Arrays INPUT nums1 (can rearrange): 5 3 2 4 nums2 (fixed order): 2 1 4 5 n = 4 nums1 = [5, 3, 2, 4] nums2 = [2, 1, 4, 5] Goal: Minimize sum of nums1[i] * nums2[i] ALGORITHM STEPS 1 Sort nums1 ASC [2, 3, 4, 5] 2 Sort nums2 DESC [5, 4, 2, 1] 3 Pair elements Small with Large 2 x 5 = 10 3 x 4 = 12 4 x 2 = 8 5 x 1 = 5 4 Calculate Sum 10 + 12 + 8 + 5 = 35 Time: O(n log n) Space: O(1) FINAL RESULT Sorted nums1 (ASC): 2 3 4 5 Sorted nums2 (DESC): 5 4 2 1 Product Sum Calculation: 2*5 + 3*4 + 4*2 + 5*1 = 10 + 12 + 8 + 5 = 35 Output 35 OK Key Insight: To minimize the product sum, pair the smallest elements of one array with the largest elements of the other. This greedy approach ensures that large values are multiplied by small values, reducing the overall sum. Sort nums1 ascending and nums2 descending, then multiply pairwise. TutorialsPoint - Minimize Product Sum of Two Arrays | Greedy Sorting Approach
Asked in
Google 15 Amazon 12 Microsoft 8
34.8K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen