carloscn / structstudy

Leetcode daily trainning by using C/C++/RUST programming.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

leetcode1913: Maximum Product Difference Between Two Pairs

carloscn opened this issue · comments

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

Analysis

pub fn max_product_difference(nums: Vec<i32>) -> i32
{
    if nums.len() < 4 {
        return 0;
    }

    let mut ret:i32 = 0;

    let (mut first_max, mut sec_max, mut first_min, mut sec_min) =
        (i32::MIN, i32::MIN + 1, i32::MAX, i32::MAX - 1);

    for i in 0..nums.len() {
        if nums[i] > first_max {
            sec_max = first_max;
            first_max = nums[i];
        } else if nums[i] <= first_max && nums[i] > sec_max {
            sec_max = nums[i];
        }

        if nums[i] < first_min {
            sec_min = first_min;
            first_min = nums[i];
        } else if nums[i] >= first_min && nums[i] < sec_min {
            sec_min = nums[i];
        }
    }

    ret = (first_max * sec_max) - (first_min * sec_min);

    return ret;
}