Skip to content

LeetCode: 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 wxy, 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

解題思路

最簡單的方法就是使用排序、然後取頭尾。然而,這個方法的時間複雜度是 O(n*log(n)),實在是不夠好。

另外一個很直覺的解法就是設定四個變數,分別代表最大、次大、最小、次小的四個數值。並且在遍歷整個輸入陣列時同步更新。

需要注意的是,如果最大的數值被取代,則原先最大的數值會再賦值給次大的變數;最小和次小的狀況同理。

如此一來,這樣的時間複雜度是 O(n)(只需要遍歷一次)並且空間複雜度是 O(1)。


C++ 範例程式碼

class Solution {
public:
    int maxProductDifference(vector<int>& nums) {
        // Init
        int max1 = INT_MIN;
        int max2 = INT_MIN;
        int min1 = INT_MAX;
        int min2 = INT_MAX;

        // Traversal
        for (int& num: nums) {
            if (num >= max1) {
                max2 = max1;
                max1 = num;
            }
            else if (num >= max2) {
                max2 = num;
            }
            
            if (num <= min1) {
                min2 = min1;
                min1 = num;
            }
            else if (num <= min2) {
                min2 = num;
            }
        }

        return max1 * max2 - min1 * min2;
    }
};



Python 範例程式碼

class Solution:
    def maxProductDifference(self, nums: List[int]) -> int:
        # Init
        max1 = -1
        max2 = -1
        min1 = 10000
        min2 = 10000

        # Traversal
        for num in nums:
            if num >= max1:
                max2 = max1
                max1 = num
            elif num >= max2:
                max2 = num
            
            if num <= min1:
                min2 = min1
                min1 = num
            elif num <= min2:
                min2 = num

        return max1 * max2 - min1 * min2





References


Read More

Leave a Reply