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:
23
💡 Note:
Select [6,3], [5,2], [3,1]: total_profit = 14, distinct_categories = 3, elegance = 14 + 3² = 23.
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code