3572. Maximize Y‑Sum by Picking a Triplet of Distinct X‑Values
Description
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
xare distinct.5 + 3 + 6 = 14is 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 <= 1051 <= x[i], y[i] <= 106
Solutions
Solution 1: Sorting + Greedy + Hash Table
Thinking
The three \(x\) values must be distinct and the objective is the sum of their \(y\)’s, so each chosen \(x\) should contribute its best \(y\). Sort pairs by \(y\) descending, record used \(x\) in a set, and add the first three new \(x\) values.
If fewer than three distinct \(x\) appear, return \(-1\). One sort and one scan suffice.
We pair the elements of arrays \(x\) and \(y\) into a 2D array \(\textit{arr}\), and then sort \(\textit{arr}\) in descending order by the value of \(y\). Next, we use a hash table to record the \(x\) values that have already been selected, and iterate through \(\textit{arr}\), each time selecting an \(x\) value and its corresponding \(y\) value that has not been chosen yet, until we have selected three distinct \(x\) values.
If we manage to select three different \(x\) values during the iteration, we return the sum of their corresponding \(y\) values; if we finish iterating without selecting three distinct \(x\) values, we return -1.
The time complexity is \(O(n \times \log n)\), and the space complexity is \(O(n)\), where \(n\) is the length of arrays \(\textit{x}\) and \(\textit{y}\).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |