Skip to content

1874. Minimize Product Sum of Two Arrays 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  int minProductSum(vector<int>& nums1, vector<int>& nums2) {
    int ans = 0;

    ranges::sort(nums1);
    ranges::sort(nums2, greater<>());

    for (int i = 0; i < nums1.size(); ++i)
      ans += nums1[i] * nums2[i];

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int minProductSum(int[] nums1, int[] nums2) {
    final int n = nums1.length;

    int ans = 0;

    Arrays.sort(nums1);
    Arrays.sort(nums2);

    for (int i = 0; i < n; ++i)
      ans += nums1[i] * nums2[n - 1 - i];

    return ans;
  }
}
1
2
3
class Solution:
  def minProductSum(self, nums1: list[int], nums2: list[int]) -> int:
    return sum([a * b for a, b in zip(sorted(nums1), sorted(nums2, reverse=True))])