#1896

Minimum Cost to Change the Final Value of Expression

Hard
MathStringDynamic ProgrammingStackDynamic ProgrammingStack
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses dynamic programming to minimize the cost of changing the expression by storing intermediate results for sub-expressions. This approach avoids redundant calculations and efficiently finds the minimum cost.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a stack to evaluate the expression and store the minimum cost to achieve both values (0 and 1) for each sub-expression.
  2. 2Step 2: For each operator, calculate the cost of changing the values based on the current operator and the values of the operands.
  3. 3Step 3: Return the minimum cost to change the final value to 0.
solution.py29 lines
1# Full working Python code
2from collections import defaultdict
3
4def min_cost_optimal(expression):
5    stack = []
6    cost_map = defaultdict(lambda: [float('inf'), float('inf')])
7    
8    for char in expression:
9        if char in '01':
10            cost_map[char] = [0, 0] if char == '1' else [1, 1]
11            stack.append(char)
12        elif char in '&|':
13            b = stack.pop()
14            a = stack.pop()
15            cost_a = cost_map[a]
16            cost_b = cost_map[b]
17            if char == '&':
18                cost_map[char] = [
19                    min(cost_a[0] + cost_b[0], cost_a[1] + cost_b[0] + 1, cost_a[0] + cost_b[1] + 1),
20                    min(cost_a[1] + cost_b[1], cost_a[1] + cost_b[0] + 1, cost_a[0] + cost_b[1] + 1)
21                ]
22            else:
23                cost_map[char] = [
24                    min(cost_a[0] + cost_b[0] + 1, cost_a[1] + cost_b[0], cost_a[0] + cost_b[1]),
25                    min(cost_a[1] + cost_b[1], cost_a[1] + cost_b[0] + 1, cost_a[0] + cost_b[1] + 1)
26                ]
27            stack.append(char)
28    return cost_map[stack[0]][0]
29

Complexity note: The time complexity is O(n) because we process each character of the expression once, and the space complexity is O(n) due to the stack and cost map used to store intermediate results.

  • 1Dynamic programming can significantly reduce redundant calculations.
  • 2Understanding operator precedence and evaluation order is crucial.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.