Skip to content

1874. Minimize Product Sum of Two Arrays 👍

  • Time: $O(n\log n)$
  • 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;

    sort(begin(nums1), end(nums1));
    sort(begin(nums2), end(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 - i - 1];

    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))])
Back to top