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: Optimal Pairing Strategynums1 = [5,3,2,4]nums2 = [2,1,4,5]5324214523455421Sorted AscendingSorted Descending2×5 + 3×4 + 4×2 + 5×1 = 10 + 12 + 8 + 5 = 35Minimum Product Sum: 35
Understanding the Visualization
1
Input
Two arrays nums1=[5,3,2,4] and nums2=[2,1,4,5]
2
Strategy
Pair smallest from nums1 with largest from nums2
3
Output
Minimum product sum = 35
Key Takeaway
🎯 Key Insight: Pair smallest elements with largest elements to minimize product sum
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