Maximum Product Difference Between Two Pairs, but with a twist
Yesterday's daily problem, E1913. Maximum Product Difference Between Two Pairs, is a very easy one.
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.
Constraints:
4 <= nums.length <= $10^4$
1 <= nums[i] <= $10^4$
This problem is very easy, one just needs to find the largest two numbers and the smallest two. This works because all the elements are positive.
So, naturally, I wonder, what if 0 and negative numbers are allowed? I.e, the second constraint becomes $-10^4$ <= nums[i] <= $10^4$?
At first, I thought, this is just a little more complicated. But as I attempted to solve it, I figured that this problem has quite a few special situations that I must take care of. It takes a lot of patience and carefulness.
Here is the test program that I wrote in C++. Are you able to solve this problem correctly? (The solution must still be $O(n)$.)
(Let me know if you translated it into a different language. I'll add them or link them.)
For simplicity and speed, the test cases are not randomly shuffled, but it probably doesn't matter too much in this context. A bigger problem is, the extreme cases are too rare, so I added some of them manually. If you think there are other extreme cases that should be included, let me know!
I wrote my own solution and it passed all test cases, but I'm still not 100% sure it's correct. Let me know if you wrote a better test case generator that covers more corner cases!