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: 24
💡 Note: Best triplet: indices 0,2,4 with x-values [1,3,2] and sum = 10+8+6 = 24

Constraints

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

Visualization

Tap to expand
Maximize Y-Sum by Picking Triplet of Distinct X-Values INPUT Arrays x and y (length n=4): i=0 i=1 i=2 i=3 x: 1 2 1 3 y: 5 8 3 9 Constraint: Pick i, j, k where x[i] != x[j] != x[k] and all three distinct Goal: Maximize y[i]+y[j]+y[k] x = [1, 2, 1, 3] y = [5, 8, 3, 9] ALGORITHM STEPS 1 Group by X value Create HashMap: x-val to y-vals map[1] = [5, 3] map[2] = [8] map[3] = [9] 2 Keep max Y per X Sort/keep top values each group x=1: max=5, x=2: max=8 x=3: max=9 3 Select top 3 distinct X Pick 3 groups with highest Y 4 Sum the max values Result = 5 + 8 + 9 5 + 8 + 9 = 22 FINAL RESULT Selected triplet: i=0: x[0]=1, y[0]=5 5 i=1: x[1]=2, y[1]=8 8 i=3: x[3]=3, y[3]=9 9 Verification: x[0]=1, x[1]=2, x[3]=3 All distinct: 1!=2!=3 [OK] OUTPUT 22 Key Insight: Use a Hash Map to group y-values by their corresponding x-values. For each unique x, keep only the maximum y-value. Then select the top 3 y-values from groups with distinct x-values. This ensures we maximize the sum while satisfying the constraint that all three x-values must be different. TutorialsPoint - Maximize Y-Sum by Picking a Triplet of Distinct X-Values | Hash Map Grouping Approach
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