Approach
Stack-based processing
For Maximum Elegance of a K-Length Subsequence, the implementation keeps unresolved items in last-in, first-out order, often to match boundaries, parse structure, or maintain monotonic candidates.
- Define what every stack entry represents.
- Pop entries once the current item resolves or invalidates them.
- Push the current item with only the information later steps need.
Code notes
- 47 lines of C++ from the credited upstream file 2813.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 2 loop blocks detected.
Complexity
If each item is pushed and popped at most once, the stack work is linear.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 long long findMaximumElegance(vector<vector<int>>& items, int k) {4 long ans = 0;5 long totalProfit = 0;6 unordered_set<int> seenCategories;7 stack<int> decreasingDuplicateProfits;8 9 ranges::sort(items, greater<>());10 11 for (int i = 0; i < k; i++) {12 const int profit = items[i][0];13 const int category = items[i][1];14 totalProfit += profit;15 if (seenCategories.contains(category))16 decreasingDuplicateProfits.push(profit);17 else18 seenCategories.insert(category);19 }20 21 ans = totalProfit +22 static_cast<long>(seenCategories.size()) * seenCategories.size();23 24 for (int i = k; i < items.size(); ++i) {25 const int profit = items[i][0];26 const int category = items[i][1];27 if (!seenCategories.contains(category) &&28 !decreasingDuplicateProfits.empty()) {29 30 31 32 33 totalProfit -= decreasingDuplicateProfits.top(),34 decreasingDuplicateProfits.pop();35 totalProfit += profit;36 seenCategories.insert(category);37 ans = max(ans,38 static_cast<long>(totalProfit +39 static_cast<long>(seenCategories.size()) *40 seenCategories.size()));41 }42 }43 44 return ans;45 }46};47