返回介绍

solution / 1900-1999 / 1913.Maximum Product Difference Between Two Pairs / README_EN

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

1913. Maximum Product Difference Between Two Pairs

中文文档

Description

The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d).

  • For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16.

Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized.

Return _the maximum such product difference_.

 

Example 1:


Input: nums = [5,6,2,7,4]

Output: 34

Explanation: We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).

The product difference is (6 * 7) - (2 * 4) = 34.

Example 2:


Input: nums = [4,2,5,9,7,4,8]

Output: 64

Explanation: We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).

The product difference is (9 * 8) - (2 * 4) = 64.

 

Constraints:

  • 4 <= nums.length <= 104
  • 1 <= nums[i] <= 104

Solutions

Solution 1

class Solution:
  def maxProductDifference(self, nums: List[int]) -> int:
    nums.sort()
    return nums[-1] * nums[-2] - nums[0] * nums[1]
class Solution {
  public int maxProductDifference(int[] nums) {
    Arrays.sort(nums);
    int n = nums.length;
    return nums[n - 1] * nums[n - 2] - nums[0] * nums[1];
  }
}
class Solution {
public:
  int maxProductDifference(vector<int>& nums) {
    sort(nums.begin(), nums.end());
    int n = nums.size();
    return nums[n - 1] * nums[n - 2] - nums[0] * nums[1];
  }
};
func maxProductDifference(nums []int) int {
  sort.Ints(nums)
  n := len(nums)
  return nums[n-1]*nums[n-2] - nums[0]*nums[1]
}
/**
 * @param {number[]} nums
 * @return {number}
 */
var maxProductDifference = function (nums) {
  nums.sort((a, b) => a - b);
  let n = nums.length;
  let ans = nums[n - 1] * nums[n - 2] - nums[0] * nums[1];
  return ans;
};

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

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

发布评论

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