Approach
Stack-based processing
For Minimum Cost to Change the Final Value of Expression, 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
- 62 lines of Java from the credited upstream file 1896.java.
- The implementation visibly relies on work queue.
- 1 loop block 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 int minOperationsToFlip(String expression) {3 4 Deque<Pair<Character, Integer>> stack = new ArrayDeque<>();5 Pair<Character, Integer> lastPair = null;6 7 for (final char e : expression.toCharArray()) {8 if (e == '(' || e == '&' || e == '|') {9 10 stack.push(new Pair<>(e, 0));11 continue;12 }13 if (e == ')') {14 lastPair = stack.pop();15 stack.pop(); 16 } else { 17 18 19 lastPair = new Pair<>(e, 1);20 }21 if (!stack.isEmpty() && (stack.peek().getKey() == '&' || stack.peek().getKey() == '|')) {22 final char op = stack.pop().getKey();23 final char a = stack.peek().getKey();24 final int costA = stack.pop().getValue();25 final char b = lastPair.getKey();26 final int costB = lastPair.getValue();27 28 if (op == '&') {29 if (a == '0' && b == '0')30 31 lastPair = new Pair<>('0', 1 + Math.min(costA, costB));32 else if (a == '0' && b == '1')33 34 lastPair = new Pair<>('0', 1);35 else if (a == '1' && b == '0')36 37 lastPair = new Pair<>('0', 1);38 else 39 40 lastPair = new Pair<>('1', Math.min(costA, costB));41 } else { 42 if (a == '0' && b == '0')43 44 lastPair = new Pair<>('0', Math.min(costA, costB));45 else if (a == '0' && b == '1')46 47 lastPair = new Pair<>('1', 1);48 else if (a == '1' && b == '0')49 50 lastPair = new Pair<>('1', 1);51 else 52 53 lastPair = new Pair<>('1', 1 + Math.min(costA, costB));54 }55 }56 stack.push(lastPair);57 }58 59 return stack.peek().getValue();60 }61}62