[LeetCode] Minimize Product Sum of Two Arrays

1874. Minimize Product Sum of Two Arrays

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 x 5 + 2 x 2 + 3 x 3 + 4 x 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.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int minProductSum(vector<int>& A, vector<int>& B) {
int sum = 0, n = A.size();
sort(begin(A), end(A));
sort(begin(B), end(B));
for(int i = 0; i < n; i++)
sum += A[i] * B[n-i-1];
return sum;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/09/PS/LeetCode/minimize-product-sum-of-two-arrays/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.