Maximize Y‑Sum by Picking a Triplet of Distinct X‑Values Problem
Description
LeetCode Problem 3572.
You are given two integer arrays x and y, each of length n. You must choose three distinct indices i, j, and k such that:
x[i] != x[j]x[j] != x[k]x[k] != x[i]
Your goal is to maximize the value of y[i] + y[j] + y[k] under these conditions. Return the maximum possible sum that can be obtained by choosing such a triplet of indices.
If no such triplet exists, return -1.
Example 1:
Input: x = [1,2,1,3,2], y = [5,3,4,6,2]
Output: 14
Explanation:
- Choose i = 0 (x[i] = 1, y[i] = 5), j = 1 (x[j] = 2, y[j] = 3), k = 3 (x[k] = 3, y[k] = 6).
- All three values chosen from x are distinct. 5 + 3 + 6 = 14 is the maximum we can obtain. Hence, the output is 14.
Example 2:
Input: x = [1,2,1,2], y = [4,5,6,7]
Output: -1
Explanation:
- There are only two distinct values in x. Hence, the output is -1.
Constraints:
n == x.length == y.length3 <= n <= 10^51 <= x[i], y[i] <= 10^6
Solution
Approach: Sort + Greedy
Pair each x[i] with y[i] and sort the pairs by y in descending order. Walk through the list and take a pair whenever its x has not been picked yet (track picked values in a set), stopping after three. The sum of their y values is the answer; if fewer than three distinct x values exist, return -1.
Taking the largest y available for each new x is optimal, since any set of three distinct x values can only improve by using each value's largest y.
Complexity: time O(n log n), space O(n).
class Solution:
def maxSumDistinctTriplet(self, x: List[int], y: List[int]) -> int:
arr = [(a, b) for a, b in zip(x, y)]
arr.sort(key=lambda x: -x[1])
vis = set()
ans = 0
for a, b in arr:
if a in vis:
continue
vis.add(a)
ans += b
if len(vis) == 3:
return ans
return -1