[LeetCode] Maximum Product Difference Between Two Pairs

1913. Maximum Product Difference Between Two Pairs

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.

1
2
3
4
5
6
7
8
9
class Solution {
public:
int maxProductDifference(vector<int>& nums) {
sort(nums.begin(), nums.end());
int sz = nums.size();
return (nums[sz - 1] * nums[sz - 2]) - (nums[0] * nums[1]);
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2021/06/27/PS/LeetCode/maximum-product-difference-between-two-pairs/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.