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. 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.

Input & Output

Example 1 — Basic Case
$ Input: x = [1,2,1,3], y = [5,8,3,9]
Output: 22
💡 Note: Choose indices 0, 1, 3: x[0]=1, x[1]=2, x[3]=3 (all different), sum = y[0]+y[1]+y[3] = 5+8+9 = 22
Example 2 — No Valid Triplet
$ Input: x = [1,1,1], y = [4,5,6]
Output: -1
💡 Note: All x-values are the same (1), so no valid triplet with distinct x-values exists
Example 3 — Multiple Options
$ Input: x = [1,2,3,1,2], y = [10,5,8,7,6]
Output: 23
💡 Note: Best triplet: indices 0,1,2 with x-values [1,2,3] and sum = 10+5+8 = 23

Constraints

  • 3 ≤ x.length = y.length ≤ 1000
  • 1 ≤ x[i] ≤ 100
  • 1 ≤ y[i] ≤ 1000

Visualization

Tap to expand
Maximize Y-Sum by Picking Distinct X-Values1213x arrayi=0i=1i=2i=35839y arraySelected indices: 0, 1, 3x-values: 1, 2, 3 (all distinct ✓)Maximum sum: 5 + 8 + 9 = 22
Understanding the Visualization
1
Input Arrays
Two arrays x and y with corresponding indices
2
Find Valid Triplet
Select 3 indices with distinct x-values
3
Maximize Sum
Choose triplet that maximizes sum of y-values
Key Takeaway
🎯 Key Insight: Group by x-values and keep only the best y-values from each group to efficiently find optimal triplet
Asked in
Google 15 Amazon 12 Microsoft 8
31.2K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen