Problem solution · C++

Maximum Elegance of a K-Length Subsequence

Maximum Elegance of a K-Length Subsequence: a C++ solution using stack-based processing. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Stack-based processing
Source
walkccc LeetCode Solutions
Length
47 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

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.

  1. Define what every stack entry represents.
  2. Pop entries once the current item resolves or invalidates them.
  3. 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.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMaximum Elegance of a K-Length Subsequence · C++C++
Use this to learn the idea, then write your own version.
class Solution { public:  long long findMaximumElegance(vector<vector<int>>& items, int k) {    long ans = 0;    long totalProfit = 0;    unordered_set<int> seenCategories;    stack<int> decreasingDuplicateProfits;     ranges::sort(items, greater<>());     for (int i = 0; i < k; i++) {      const int profit = items[i][0];      const int category = items[i][1];      totalProfit += profit;      if (seenCategories.contains(category))        decreasingDuplicateProfits.push(profit);      else        seenCategories.insert(category);    }     ans = totalProfit +          static_cast<long>(seenCategories.size()) * seenCategories.size();     for (int i = k; i < items.size(); ++i) {      const int profit = items[i][0];      const int category = items[i][1];      if (!seenCategories.contains(category) &&          !decreasingDuplicateProfits.empty()) {        // If this is a new category we haven't seen before, it's worth        // considering taking it and replacing the one with the least profit        // since it will increase the distinct_categories and potentially result        // in a larger total_profit + distinct_categories^2.        totalProfit -= decreasingDuplicateProfits.top(),            decreasingDuplicateProfits.pop();        totalProfit += profit;        seenCategories.insert(category);        ans = max(ans,                  static_cast<long>(totalProfit +                                    static_cast<long>(seenCategories.size()) *                                        seenCategories.size()));      }    }     return ans;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗