Maximize Y‑Sum by Picking a Triplet of Distinct X‑Values
MedPrompt
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
Approaches
3 approaches with complexity analysis and trade-offs.
This approach first simplifies the problem by preprocessing the input arrays. We are interested in maximizing the sum of y values for three distinct x values. If multiple points share the same x coordinate, we only need to consider the one with the largest y value for that x. We can use a hash map to store the maximum y for each unique x. After preprocessing, we have a collection of unique (x, y_max) pairs. Then, we can iterate through all possible combinations of three pairs from this collection, calculate their y-sum, and keep track of the maximum sum found.
Algorithm
- Preprocessing:
- Create a
HashMap<Integer, Integer>calledmax_y_for_xto store the maximumyvalue for each uniquexcoordinate. - Iterate through the input arrays
xandy. For each pair(x[i], y[i]), update the map:max_y_for_x.put(x[i], Math.max(max_y_for_x.getOrDefault(x[i], 0), y[i])).
- Create a
- Feasibility Check:
- If the number of unique
xvalues (max_y_for_x.size()) is less than 3, return -1.
- If the number of unique
- Brute-Force Triplet Selection:
- Convert the map's entries into a
Listof pairs, let's call itpoints. - Initialize a variable
maxSumto -1. - Use three nested loops to iterate through all unique combinations of three points from the
pointslist. - For each combination, calculate the sum of their
yvalues. - Update
maxSumif the current sum is greater.
- Convert the map's entries into a
- Return Result:
- Return
maxSum.
- Return
Walkthrough
The core idea is to first reduce the problem space. Since we need to pick three points with distinct x coordinates, for any given x coordinate that appears multiple times, we only ever need to consider the point with the highest y coordinate. This is because picking any other point with the same x coordinate would result in a smaller or equal sum.
- Preprocessing: We iterate through the
npoints and use aHashMapto store the maximumyvalue seen for eachxvalue. The key of the map is thexcoordinate, and the value is the maximumycoordinate found for it. - Triplet Search: After populating the map, we have a set of unique
xcoordinates and their corresponding bestyvalues. If this set has fewer than three entries, it's impossible to form a valid triplet, so we return -1. Otherwise, we convert the map entries to a list and use a brute-force method with three nested loops to check every possible combination of three distinct entries. For each combination, we sum theiryvalues and update our overall maximum sum.
import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map; class Solution { public long maximumTripletValue(int[] x, int[] y) { Map<Integer, Integer> maxYForX = new HashMap<>(); for (int i = 0; i < x.length; i++) { maxYForX.put(x[i], Math.max(maxYForX.getOrDefault(x[i], 0), y[i])); } if (maxYForX.size() < 3) { return -1; } List<Map.Entry<Integer, Integer>> points = new ArrayList<>(maxYForX.entrySet()); long maxSum = -1; int m = points.size(); for (int i = 0; i < m; i++) { for (int j = i + 1; j < m; j++) { for (int k = j + 1; k < m; k++) { long currentSum = (long) points.get(i).getValue() + points.get(j).getValue() + points.get(k).getValue(); if (maxSum == -1 || currentSum > maxSum) { maxSum = currentSum; } } } } return maxSum; }}Complexity
Time
O(n + m^3), where `n` is the length of the input arrays and `m` is the number of unique `x` values. The preprocessing step takes O(n). The three nested loops take O(m^3). In the worst case, `m` can be up to `n`, leading to a time complexity of O(n^3).
Space
O(m), where `m` is the number of unique `x` values. In the worst case, all `x` values are unique, so `m = n`, leading to O(n) space complexity for the map and the list.
Trade-offs
Pros
Conceptually simple and easy to understand.
The preprocessing step correctly simplifies the problem.
Cons
Extremely inefficient due to the cubic time complexity.
Will result in a 'Time Limit Exceeded' (TLE) error for large inputs as specified in the constraints.
Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.