Maximize Y‑Sum by Picking a Triplet of Distinct X‑Values

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
Inputx = [1,2,1,3,2], y = [5,3,4,6,2]
Output14
All three values chosen from x are distinct, and 5 + 3 + 6 = 14 is the maximum obtainable sum.
Example 2
Inputx = [1,2,1,2], y = [4,5,6,7]
Output-1
There are only two distinct values in x, so no valid triplet exists.

Constraints

  • n == x.length == y.length
  • 3 <= n <= 10^5
  • 1 <= x[i], y[i] <= 10^6

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate