Input: nums1 =[5,3,4,2], nums2 =[4,2,2,5]Output: 40Explanation: We can rearrange nums1 to become [3,5,4,2]. The product sum of [3,5,4,2] and [4,2,2,5]is3*4+5*2+4*2+2*5=40.
Example 2:
1
2
3
Input: nums1 =[2,1,4,5,7], nums2 =[3,2,4,8,6]Output: 65Explanation: We can rearrange nums1 to become [5,7,4,1,2]. The product sum of [5,7,4,1,2] and [3,2,4,8,6]is5*3+7*2+4*4+1*8+2*6=65.
To minimize the product sum, pair the smallest elements of one array with the largest elements of the other. This way, large values are multiplied by small values, reducing the total sum.
classSolution {
publicintminProductSum(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int ans = 0, n = nums1.length;
for (int i = 0; i < n; ++i) ans += nums1[i]* nums2[n-1-i];
return ans;
}
}
1
2
3
4
5
6
7
8
9
classSolution {
funminProductSum(nums1: IntArray, nums2: IntArray): Int {
nums1.sort()
nums2.sortDescending()
var ans = 0for (i in nums1.indices) ans += nums1[i] * nums2[i]
return ans
}
}
1
2
3
4
5
6
7
defmin_product_sum(nums1: list[int], nums2: list[int]) -> int:
nums1.sort()
nums2.sort(reverse=True)
ans =0for a, b in zip(nums1, nums2):
ans += a * b
return ans
1
2
3
4
5
6
7
8
9
impl Solution {
pubfnmin_product_sum(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 {
letmut a = nums1.clone();
letmut b = nums2.clone();
a.sort();
b.sort_by(|x, y| y.cmp(x));
a.iter().zip(b.iter()).map(|(x, y)| x * y).sum()
}
}
1
2
3
4
5
6
7
8
9
classSolution {
minProductSum(nums1: number[], nums2: number[]):number {
nums1.sort((a, b) =>a-b);
nums2.sort((a, b) =>b-a);
letans=0;
for (leti=0; i<nums1.length; ++i) ans+=nums1[i] *nums2[i];
returnans;
}
}