- 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
- 53 lines of Java from the credited upstream file 1628.java.
- The implementation visibly relies on sequence storage, ordered lookup, work queue.
- 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 6abstract class Node {7 public abstract int evaluate();8 9};10 11class ExpNode extends Node {12 public ExpNode(String val, ExpNode left, ExpNode right) {13 this.val = val;14 this.left = left;15 this.right = right;16 }17 18 public int evaluate() {19 if (left == null && right == null)20 return Integer.parseInt(val);21 return op.get(val).apply(left.evaluate(), right.evaluate());22 }23 24 private static final Map<String, BinaryOperator<Integer>> op =25 Map.of("+", (a, b) -> a + b, "-", (a, b) -> a - b, "*", (a, b) -> a *b, "/", (a, b) -> a / b);26 private final String val;27 private final ExpNode left;28 private final ExpNode right;29}30 31/**32 * This is the TreeBuilder class.33 * You can treat it as the driver code that takes the postinfix input34 * and returns the expression tree represnting it as a Node.35 */36 37class TreeBuilder {38 Node buildTree(String[] postfix) {39 Deque<ExpNode> stack = new ArrayDeque<>();40 41 for (final String val : postfix)42 if (val.equals("+") || val.equals("-") || val.equals("*") || val.equals("/")) {43 ExpNode right = stack.pop();44 ExpNode left = stack.pop();45 stack.push(new ExpNode(val, left, right));46 } else {47 stack.push(new ExpNode(val, null, null));48 }49 50 return stack.pop();51 }52}53