#3572
Maximize Y‑Sum by Picking a Triplet of Distinct X‑Values
MediumArrayHash TableGreedySortingHeap (Priority Queue)Hash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
By storing the maximum y-value for each unique x-value, we can efficiently find the top three distinct x-values and their corresponding y-values to maximize the sum.
⚙️
Algorithm
3 steps- 1Step 1: Create a dictionary to store the maximum y-value for each unique x-value.
- 2Step 2: Iterate through the arrays and populate the dictionary.
- 3Step 3: Extract the top three maximum y-values from the dictionary and return their sum.
solution.py8 lines
1def max_y_sum_optimal(x, y):
2 from collections import defaultdict
3 max_y = defaultdict(int)
4 for xi, yi in zip(x, y):
5 max_y[xi] = max(max_y[xi], yi)
6 if len(max_y) < 3:
7 return -1
8 return sum(sorted(max_y.values(), reverse=True)[:3])ℹ
Complexity note: The time complexity is dominated by sorting the unique y-values, while space is used to store the maximum y-values for distinct x-values.
- 1Use a dictionary to track maximum values for unique keys.
- 2Sorting helps in quickly finding the top values.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.