Maximum Product Difference Between Two Pairs

easy array math

Problem

Pick four distinct indices a,b,c,d in nums and return the largest (nums[a]·nums[b]) − (nums[c]·nums[d]).

Inputnums = [5,6,2,7,4]
Output34
Top two = 7,6; bottom two = 2,4 → 42 − 8 = 34.

def max_product_difference(nums):
    a = b = 0  # top 2
    c = d = float('inf')  # bottom 2
    for x in nums:
        if x >= a: b, a = a, x
        elif x > b: b = x
        if x <= c: d, c = c, x
        elif x < d: d = x
    return a * b - c * d
function maxProductDifference(nums) {
  let a = 0, b = 0, c = Infinity, d = Infinity;
  for (const x of nums) {
    if (x >= a) { b = a; a = x; }
    else if (x > b) b = x;
    if (x <= c) { d = c; c = x; }
    else if (x < d) d = x;
  }
  return a * b - c * d;
}
class Solution {
    public int maxProductDifference(int[] nums) {
        int a = 0, b = 0, c = Integer.MAX_VALUE, d = Integer.MAX_VALUE;
        for (int x : nums) {
            if (x >= a) { b = a; a = x; } else if (x > b) b = x;
            if (x <= c) { d = c; c = x; } else if (x < d) d = x;
        }
        return a * b - c * d;
    }
}
int maxProductDifference(vector<int>& nums) {
    int a = 0, b = 0, c = INT_MAX, d = INT_MAX;
    for (int x : nums) {
        if (x >= a) { b = a; a = x; } else if (x > b) b = x;
        if (x <= c) { d = c; c = x; } else if (x < d) d = x;
    }
    return a * b - c * d;
}
Time: O(n) Space: O(1)