- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 62 lines of C++ from the credited upstream file 1628.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 1 loop block detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1/**2 * This is the interface for the expression tree Node.3 * You should not remove it, and you can define some classes to implement it.4 */5 6class Node {7 public:8 virtual ~Node() {};9 virtual int evaluate() const = 0;10 11 protected:12 13};14 15class ExpNode : public Node {16 public:17 ExpNode(const string& val, ExpNode* left, ExpNode* right)18 : val(val), left(left), right(right) {}19 20 int evaluate() const override {21 return left == nullptr && right == nullptr22 ? stoi(val)23 : op.at(val)(left->evaluate(), right->evaluate());24 }25 26 private:27 static const inline unordered_map<string, function<long(long, long)>> op{28 {"+", std::plus<long>()},29 {"-", std::minus<long>()},30 {"*", std::multiplies<long>()},31 {"/", std::divides<long>()}};32 const string val;33 const ExpNode* const left;34 const ExpNode* const right;35};36 37/**38 * This is the TreeBuilder class.39 * You can treat it as the driver code that takes the postinfix input40 * and returns the expression tree represnting it as a Node.41 */42 43class TreeBuilder {44 public:45 Node* buildTree(vector<string>& postfix) {46 stack<ExpNode*> stack;47 48 for (const string& val : postfix)49 if (val == "+" || val == "-" || val == "*" || val == "/") {50 ExpNode* right = stack.top();51 stack.pop();52 ExpNode* left = stack.top();53 stack.pop();54 stack.push(new ExpNode(val, left, right));55 } else {56 stack.push(new ExpNode(val, nullptr, nullptr));57 }58 59 return stack.top();60 }61};62