Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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_categories2, 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.
Note: A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order.
Example 1:
Input: items = [[3,2],[5,1],[10,1]], k = 2 Output: 17 Explanation: In this example, we have to select a subsequence of size 2. We can select items[0] = [3,2] and items[2] = [10,1]. The total profit in this subsequence is 3 + 10 = 13, and the subsequence contains 2 distinct categories [2,1]. Hence, the elegance is 13 + 22 = 17, and we can show that it is the maximum achievable elegance.
Example 2:
Input: items = [[3,1],[3,1],[2,2],[5,3]], k = 3 Output: 19 Explanation: In this example, we have to select a subsequence of size 3. We can select items[0] = [3,1], items[2] = [2,2], and items[3] = [5,3]. The total profit in this subsequence is 3 + 2 + 5 = 10, and the subsequence contains 3 distinct categories [1,2,3]. Hence, the elegance is 10 + 32 = 19, and we can show that it is the maximum achievable elegance.
Example 3:
Input: items = [[1,1],[2,1],[3,1]], k = 3 Output: 7 Explanation: In this example, we have to select a subsequence of size 3. We should select all the items. The total profit will be 1 + 2 + 3 = 6, and the subsequence contains 1 distinct category [1]. Hence, the maximum elegance is 6 + 12 = 7.
Constraints:
1 <= items.length == n <= 105items[i].length == 2items[i][0] == profitiitems[i][1] == categoryi1 <= profiti <= 1091 <= categoryi <= n 1 <= k <= nProblem summary: 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_categories2, 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. Note: A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the remaining elements' relative order.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Stack · Greedy
[[3,2],[5,1],[10,1]] 2
[[3,1],[3,1],[2,2],[5,3]] 3
[[1,1],[2,1],[3,1]] 3
ipo)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2813: Maximum Elegance of a K-Length Subsequence
class Solution {
public long findMaximumElegance(int[][] items, int k) {
Arrays.sort(items, (a, b) -> b[0] - a[0]);
int n = items.length;
long tot = 0;
Set<Integer> vis = new HashSet<>();
Deque<Integer> dup = new ArrayDeque<>();
for (int i = 0; i < k; ++i) {
int p = items[i][0], c = items[i][1];
tot += p;
if (!vis.add(c)) {
dup.push(p);
}
}
long ans = tot + (long) vis.size() * vis.size();
for (int i = k; i < n; ++i) {
int p = items[i][0], c = items[i][1];
if (vis.contains(c) || dup.isEmpty()) {
continue;
}
vis.add(c);
tot += p - dup.pop();
ans = Math.max(ans, tot + (long) vis.size() * vis.size());
}
return ans;
}
}
// Accepted solution for LeetCode #2813: Maximum Elegance of a K-Length Subsequence
func findMaximumElegance(items [][]int, k int) int64 {
sort.Slice(items, func(i, j int) bool { return items[i][0] > items[j][0] })
tot := 0
vis := map[int]bool{}
dup := []int{}
for _, item := range items[:k] {
p, c := item[0], item[1]
tot += p
if vis[c] {
dup = append(dup, p)
} else {
vis[c] = true
}
}
ans := tot + len(vis)*len(vis)
for _, item := range items[k:] {
p, c := item[0], item[1]
if vis[c] || len(dup) == 0 {
continue
}
vis[c] = true
tot += p - dup[len(dup)-1]
dup = dup[:len(dup)-1]
ans = max(ans, tot+len(vis)*len(vis))
}
return int64(ans)
}
# Accepted solution for LeetCode #2813: Maximum Elegance of a K-Length Subsequence
class Solution:
def findMaximumElegance(self, items: List[List[int]], k: int) -> int:
items.sort(key=lambda x: -x[0])
tot = 0
vis = set()
dup = []
for p, c in items[:k]:
tot += p
if c not in vis:
vis.add(c)
else:
dup.append(p)
ans = tot + len(vis) ** 2
for p, c in items[k:]:
if c in vis or not dup:
continue
vis.add(c)
tot += p - dup.pop()
ans = max(ans, tot + len(vis) ** 2)
return ans
// Accepted solution for LeetCode #2813: Maximum Elegance of a K-Length Subsequence
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #2813: Maximum Elegance of a K-Length Subsequence
// class Solution {
// public long findMaximumElegance(int[][] items, int k) {
// Arrays.sort(items, (a, b) -> b[0] - a[0]);
// int n = items.length;
// long tot = 0;
// Set<Integer> vis = new HashSet<>();
// Deque<Integer> dup = new ArrayDeque<>();
// for (int i = 0; i < k; ++i) {
// int p = items[i][0], c = items[i][1];
// tot += p;
// if (!vis.add(c)) {
// dup.push(p);
// }
// }
// long ans = tot + (long) vis.size() * vis.size();
// for (int i = k; i < n; ++i) {
// int p = items[i][0], c = items[i][1];
// if (vis.contains(c) || dup.isEmpty()) {
// continue;
// }
// vis.add(c);
// tot += p - dup.pop();
// ans = Math.max(ans, tot + (long) vis.size() * vis.size());
// }
// return ans;
// }
// }
// Accepted solution for LeetCode #2813: Maximum Elegance of a K-Length Subsequence
function findMaximumElegance(items: number[][], k: number): number {
items.sort((a, b) => b[0] - a[0]);
let tot = 0;
const vis: Set<number> = new Set();
const dup: number[] = [];
for (const [p, c] of items.slice(0, k)) {
tot += p;
if (vis.has(c)) {
dup.push(p);
} else {
vis.add(c);
}
}
let ans = tot + vis.size ** 2;
for (const [p, c] of items.slice(k)) {
if (vis.has(c) || dup.length === 0) {
continue;
}
tot += p - dup.pop()!;
vis.add(c);
ans = Math.max(ans, tot + vis.size ** 2);
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
For each element, scan left (or right) to find the next greater/smaller element. The inner scan can visit up to n elements per outer iteration, giving O(n²) total comparisons. No extra space needed beyond loop variables.
Each element is pushed onto the stack at most once and popped at most once, giving 2n total operations = O(n). The stack itself holds at most n elements in the worst case. The key insight: amortized O(1) per element despite the inner while-loop.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Pushing without popping stale elements invalidates next-greater/next-smaller logic.
Usually fails on: Indices point to blocked elements and outputs shift.
Fix: Pop while invariant is violated before pushing current element.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.