返回介绍

solution / 1800-1899 / 1874.Minimize Product Sum of Two Arrays / README_EN

发布于 2024-06-17 01:03:13 字数 3245 浏览 0 评论 0 收藏 0

1874. Minimize Product Sum of Two Arrays

中文文档

Description

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

 

Example 1:


Input: nums1 = [5,3,4,2], nums2 = [4,2,2,5]

Output: 40

Explanation: We can rearrange nums1 to become [3,5,4,2]. The product sum of [3,5,4,2] and [4,2,2,5] is 3*4 + 5*2 + 4*2 + 2*5 = 40.

Example 2:


Input: nums1 = [2,1,4,5,7], nums2 = [3,2,4,8,6]

Output: 65

Explanation: 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] is 5*3 + 7*2 + 4*4 + 1*8 + 2*6 = 65.

 

Constraints:

  • n == nums1.length == nums2.length
  • 1 <= n <= 105
  • 1 <= nums1[i], nums2[i] <= 100

Solutions

Solution 1

class Solution:
  def minProductSum(self, nums1: List[int], nums2: List[int]) -> int:
    nums1.sort()
    nums2.sort()
    n, res = len(nums1), 0
    for i in range(n):
      res += nums1[i] * nums2[n - i - 1]
    return res
class Solution {
  public int minProductSum(int[] nums1, int[] nums2) {
    Arrays.sort(nums1);
    Arrays.sort(nums2);
    int n = nums1.length, res = 0;
    for (int i = 0; i < n; ++i) {
      res += nums1[i] * nums2[n - i - 1];
    }
    return res;
  }
}
class Solution {
public:
  int minProductSum(vector<int>& nums1, vector<int>& nums2) {
    sort(nums1.begin(), nums1.end());
    sort(nums2.begin(), nums2.end());
    int n = nums1.size(), res = 0;
    for (int i = 0; i < n; ++i) {
      res += nums1[i] * nums2[n - i - 1];
    }
    return res;
  }
};
func minProductSum(nums1 []int, nums2 []int) int {
  sort.Ints(nums1)
  sort.Ints(nums2)
  res, n := 0, len(nums1)
  for i, num := range nums1 {
    res += num * nums2[n-i-1]
  }
  return res
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文