Maximize Y‑Sum by Picking a Triplet of Distinct X‑Values - Problem
You are given two integer arrays x and y, each of length n. Think of these as coordinate pairs where (x[i], y[i]) represents a point with an x-coordinate and a corresponding y-value.
Your challenge is to select three distinct indices i, j, and k such that all three corresponding x-values are different:
x[i] ≠ x[j]x[j] ≠ x[k]x[k] ≠ x[i]
Your goal is to maximize the sum y[i] + y[j] + y[k] under these constraints.
Example: If x = [1, 2, 1, 3] and y = [10, 5, 8, 12], you could pick indices (1, 3, 0) giving x-values [2, 3, 1] (all distinct) with y-sum = 5 + 12 + 10 = 27.
Return the maximum possible sum, or -1 if no valid triplet exists.
Input & Output
example_1.py — Standard Case
$
Input:
x = [1, 2, 1, 3], y = [10, 5, 8, 12]
›
Output:
27
💡 Note:
We can choose indices (0, 1, 3) giving x-values [1, 2, 3] (all distinct) and y-sum = 10 + 5 + 12 = 27. This is the maximum possible.
example_2.py — Multiple Options
$
Input:
x = [1, 1, 2, 2, 3], y = [5, 10, 3, 8, 12]
›
Output:
30
💡 Note:
Best choice is indices (1, 3, 4) with x-values [1, 2, 3] and y-sum = 10 + 8 + 12 = 30. We pick the highest y-value for each distinct x-value.
example_3.py — Insufficient Distinct Values
$
Input:
x = [1, 1, 2, 2], y = [10, 5, 8, 3]
›
Output:
-1
💡 Note:
We only have 2 distinct x-values (1 and 2), but we need 3 distinct x-values to form a valid triplet.
Constraints
- 3 ≤ n ≤ 105
- 1 ≤ x[i] ≤ 105
- -105 ≤ y[i] ≤ 105
- At least 3 distinct x-values must exist for a valid solution
Visualization
Tap to expand
Understanding the Visualization
1
City Mapping
Group restaurants by city (x-value) and identify the best ones in each city
2
Smart Selection
From each of 3 different cities, pick the highest-rated restaurant
3
Maximum Experience
The combination gives the highest total rating experience
Key Takeaway
🎯 Key Insight: Group by x-values (cities) and pick the best y-values (ratings) from exactly 3 different groups to maximize the sum!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code