Leetcode 1913. Maximum Product Difference Between Two Pairs
Given an integer array nums
, choose four distinct indices w
, x
, y
, and z
such that the product difference between the two pairs (nums[w] * nums[x])
and (nums[y] * nums[z])
is maximized.
Return the maximum product difference.
nums
has at least 4 elements.nums
are non-negative integers.To achieve the maximum product difference, notice that:
Steps:
nums
in ascending order.#include <iostream>
#include <vector>
#include <algorithm>
int maxProductDifference(std::vector<int>& nums) {
std::sort(nums.begin(), nums.end());
int n = nums.size();
int maxProduct = nums[n-1] * nums[n-2];
int minProduct = nums[0] * nums[1];
return maxProduct - minProduct;
}
int main() {
std::vector<int> nums = {5, 6, 2, 7, 4};
std::cout << "Maximum Product Difference: " << maxProductDifference(nums) << std::endl;
return 0;
}
Therefore, the overall time complexity is (O(n \log n)).
This strategy ensures that we efficiently compute the maximum product difference as required by identifying the largest and smallest numbers through sorting.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?