Talentd
FleetCode

4074. Maximum Product Pair With Target Sum

Easy46.4% acceptance

You are given an integer array nums and an integer target.

A pair of distinct indices (i, j) is valid if:

  • nums[i] + nums[j] == target
  • nums[i] > nums[j]

Return a valid pair [i, j] whose product nums[i] * nums[j] is maximum among all valid pairs. If no valid pair exists, return [-1, -1].

If multiple valid pairs achieve the maximum product, you may return any of them.

Example 1:

Input: nums = [1,2,3,4], target = 5

Output: [2,1]

Explanation:

There are 2 valid pairs:

No. (i, j) nums[i] nums[j] Sum Product
1 (3, 0) 4 1 5 4
2 (2, 1) 3 2 5 6

Both pairs sum to 5 and satisfy nums[i] > nums[j]. The second pair has the larger product, 3 * 2 = 6, so the answer is [2, 1].

Example 2:

Input: nums = [-3,-1,4,2], target = 1

Output: [3,1]

Explanation:

There are 2 valid pairs:

No. (i, j) nums[i] nums[j] Sum Product
1 (2, 0) 4 -3 1 -12
2 (3, 1) 2 -1 1 -2

Since -2 > -12, the pair at indices (3, 1) is chosen and the answer is [3, 1].

Example 3:

Input: nums = [3,3,5], target = 6

Output: [-1,-1]

Explanation:

​​​​​​​No valid pair exists, since nums[0] and nums[1] sum to 6 but are equal.

Constraints:

  • 2 <= nums.length <= 100
  • -100 <= nums[i], target <= 100​​​​​​​

Hints open one at a time

Hint 1
1a (Enumeration): Enumerate every pair of indices and check whether their values sum to target and are different..
Hint 2
1b (Enumeration): Keep the valid pair with the largest product, even if that product is negative. Return the index of the larger value first.
Hint 3
2a (Hash Map): Store an index for each value. For a value x, its required partner is target - x.
Hint 4
2b (Hash Map): Ignore partners equal to x. Compare the products of the remaining matching pairs and return their indices in the required order.
Hint 5
3a (Sorting and Two Pointers): Sort the values together with their original indices, then use two pointers to find pairs summing to target.
Hint 6
3b (Sorting and Two Pointers): Among matching pairs with different values, keep the one with the largest product and return the original indices, with the larger value first
4:03
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def maxProductPair(self, nums: list[int], target: int) -> list[int]:
3
Starter codePython 3Spaces: 4
Examples
Input
[1,2,3,4]
5
Input
[-3,-1,4,2]
1
Input
[3,3,5]
6
Your code is saved on this device.Solution