Advertisement
JadonChan

solution.h

Mar 21st, 2025
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.11 KB | None | 0 0
  1. //
  2. // Created by Jadon Chan on 2025/3/21.
  3. //
  4.  
  5. #ifndef MINIMAL_LARGER_SUFFIX_SOLUTION_H
  6. #define MINIMAL_LARGER_SUFFIX_SOLUTION_H
  7.  
  8. #include <vector>
  9. #include <stack>
  10.  
  11. class solution {
  12. public:
  13.     std::vector<int> minimal_larger_suffix(std::vector<int> vec) {
  14.         std::stack<int> stk;
  15.         int n = static_cast<int>(vec.size());
  16.         int index_of_top = n;
  17.         std::vector<int> ret(n);
  18.         for (auto i = n - 1; i >= 0; i--) {
  19.             int ans;
  20.             if (stk.empty()) { // Initial state
  21.                 ans = -1;
  22.             }
  23.             // If top element is less than or equal to elem i,
  24.             // there's no element larger than elem i between elem i and elem index_of_top.
  25.             // Thus, the answer for this position is behind index_of_top. So it's the same as answer for index_of_top
  26.             else if (stk.top() <= vec[i]) {
  27.                 ans = ret[index_of_top];
  28.             }
  29.             // If top element is greater than elem i,
  30.             // the answer is the last popped element
  31.             while(!stk.empty() && stk.top() > vec[i]) {
  32.                 ans = stk.top();
  33.                 stk.pop();
  34.             }
  35.             ret[i] = ans;
  36.             stk.push(vec[i]);
  37.             index_of_top = i;
  38.         }
  39.         return ret;
  40.     }
  41. };
  42.  
  43. #endif //MINIMAL_LARGER_SUFFIX_SOLUTION_H
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement