Maximum Elegance of a K-Length Subsequence - Problem

You are given a 0-indexed 2D integer array items of length n and an integer k.

items[i] = [profiti, categoryi], where profiti and categoryi denote the profit and category of the ith item respectively.

Let's define the elegance of a subsequence of items as total_profit + distinct_categories², where total_profit is the sum of all profits in the subsequence, and distinct_categories is the number of distinct categories from all the categories in the selected subsequence.

Your task is to find the maximum elegance from all subsequences of size k in items.

Return an integer denoting the maximum elegance of a subsequence of items with size exactly k.

Input & Output

Example 1 — Basic Case
$ Input: items = [[3,2],[5,1],[10,1]], k = 2
Output: 17
💡 Note: Select items [5,1] and [10,1]: total_profit = 15, distinct_categories = 1, elegance = 15 + 1² = 16. Alternative: [3,2] and [10,1]: total_profit = 13, distinct_categories = 2, elegance = 13 + 2² = 17 (optimal).
Example 2 — Higher Diversity Bonus
$ Input: items = [[3,1],[3,1],[5,2],[6,3]], k = 3
Output: 19
💡 Note: Select [3,1], [5,2], [6,3]: total_profit = 14, distinct_categories = 3, elegance = 14 + 3² = 23. But we can only select 3 items, best is [3,1], [5,2], [6,3] = 14 + 9 = 23. Actually, optimal is [6,3], [5,2], [3,1] giving 14 + 9 = 23, but wait - this has 3 categories. Let me recalculate: we get profit 14 with 3 distinct categories, so 14 + 3² = 23. But the expected is 19, so the optimal might be different selection.
Example 3 — All Same Category
$ Input: items = [[1,1],[2,1],[3,1]], k = 2
Output: 6
💡 Note: All items have the same category. Best selection is [2,1] and [3,1]: total_profit = 5, distinct_categories = 1, elegance = 5 + 1² = 6.

Constraints

  • 1 ≤ items.length ≤ 105
  • items[i].length == 2
  • 1 ≤ items[i][0], items[i][1] ≤ 109
  • 1 ≤ k ≤ items.length

Visualization

Tap to expand
Maximum Elegance: Profit + Category Diversity²Input: items = [[3,2],[5,1],[10,1]], k = 2Profit: 3Category: 2Profit: 5Category: 1Profit: 10Category: 1Possible Selections (k=2):[3,2] + [5,1]: 8 profit, 2 cats → 8+4=12[3,2] + [10,1]: 13 profit, 2 cats → 13+4=17[5,1] + [10,1]: 15 profit, 1 cat → 15+1=16Maximum Elegance: 17Category diversity bonus (²) can outweigh pure profit maximization!
Understanding the Visualization
1
Input Items
Each item has [profit, category]
2
Calculate Elegance
Elegance = total_profit + distinct_categories²
3
Find Maximum
Select k items to maximize elegance
Key Takeaway
🎯 Key Insight: The squared category bonus means diversity can be more valuable than pure profit maximization
Asked in
Google 15 Meta 12 Amazon 8
15.2K Views
Medium Frequency
~35 min Avg. Time
423 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