QAOA for 0/1 Knapsack Problem
What You'll Learn:
- How to map a constrained optimization problem to an unconstrained QUBO formulation
- How penalty terms enforce constraints in variational quantum algorithms
- How QAOA encodes value maximization and weight constraints into a single cost Hamiltonian
- How to tune the penalty parameter P for the right balance between feasibility and exploration
Level: Intermediate | Time: 30 minutes | Qubits: 4 | Framework: Qiskit
Prerequisites
- QAOA MaxCut — QAOA fundamentals, cost/mixer operators, parameter optimization
- Bell State — entanglement basics
- Grover's Search — quantum search over bitstrings
The Idea
Imagine you're packing a backpack for a hike. You have four items — a water bottle, snacks, a first-aid kit, and a camera — each with a different value to you and a different weight. Your backpack has a weight limit. Which items do you pack to maximize value without breaking the strap?
That's the 0/1 Knapsack problem: given n items with values and weights, select a subset to maximize total value without exceeding a weight capacity C. It's NP-hard and appears everywhere from logistics to portfolio selection.
The key challenge versus MaxCut: Knapsack has a constraint (weight limit). QAOA needs unconstrained objectives, so we use the QUBO (Quadratic Unconstrained Binary Optimization) trick: fold the constraint into the objective as a quadratic penalty. The penalty parameter P controls how strongly we enforce the weight limit.
How It Works
The Problem
Given 4 items, select a subset maximizing value within weight capacity:
CODEItem 0: value=10, weight=5 Item 1: value=15, weight=8 Item 2: value=20, weight=10 Item 3: value=25, weight=12 Capacity: 18 Optimal value 35, reached by items {1, 2} (weight 18, exactly at capacity) and by items {0, 3} (weight 17)
The QUBO Formulation
We convert the constrained problem to an unconstrained one:
CODEMinimize: -Σ vᵢxᵢ + P × (Σ wᵢxᵢ - C)² ├─ value ─┤ ├─ penalty ────────┤
The penalty term (Σ wᵢxᵢ - C)² expands into linear and quadratic terms:
CODEP × [Σᵢ wᵢ²xᵢ + 2Σᵢ<ⱼ wᵢwⱼxᵢxⱼ - 2C Σᵢ wᵢxᵢ + C²] ├─ linear ─┤ ├─ quadratic ────┤ ├─ linear ─┤ const
Since xᵢ ∈ {0,1} and xᵢ² = xᵢ, every term maps to single-qubit (RZ) or two-qubit (RZZ) rotations.
Note that this squared penalty is zero only when the total weight equals C exactly, so it encodes "fill to exactly C", not "at most C". The optimal subset {0, 3} (weight 17) pays P × 1² = 25, and the empty knapsack pays P × C² = 8100, the worst of all 16 subsets. The standard fix adds extra binary variables that encode the knapsack's actual total weight (Lucas 2014, Section 5.2). This 4-item example happens to have an optimum at exactly C.
The QAOA Circuit
CODE┌───┐ ┌──────────┐ ┌─────────────────┐ ┌──────────┐ ┌─────────┐ q_0: ┤ H ├─┤ RZ(value)├─┤ RZZ(penalty,0-1)├─┤ RZ(pen.) ├─┤ RX(2β) ├── measure ├───┤ ├──────────┤ ├─────────────────┤ ├──────────┤ ├─────────┤ q_1: ┤ H ├─┤ RZ(value)├─┤ RZZ(penalty,0-2)├─┤ RZ(pen.) ├─┤ RX(2β) ├── measure ├───┤ ├──────────┤ ├─────────────────┤ ├──────────┤ ├─────────┤ q_2: ┤ H ├─┤ RZ(value)├─┤ RZZ(penalty,1-2)├─┤ RZ(pen.) ├─┤ RX(2β) ├── measure ├───┤ ├──────────┤ ├─────────────────┤ ├──────────┤ ├─────────┤ q_3: ┤ H ├─┤ RZ(value)├─┤ RZZ(penalty,...) ├─┤ RZ(pen.) ├─┤ RX(2β) ├── measure └───┘ └──────────┘ └─────────────────┘ └──────────┘ └─────────┘ ├─── Cost (value + penalty) ──────────────────┤├─ Mixer ─┤
Note: The cost layer has three sub-parts (value RZ, penalty RZZ, penalty RZ), whereas MaxCut has only one (RZZ per edge). This reflects the richer structure of constrained problems.
Step 1: Uniform Superposition
All qubits start in |+⟩ — equal probability over all 2⁴ = 16 possible item subsets.
Step 2: Cost Operator (Value Terms)
Apply RZ(γ * vᵢ) on each qubit i, from -vᵢxᵢ = -vᵢ/2 + (vᵢ/2)Zᵢ. An included item has Zᵢ = -1, so this lowers the energy of including high-value items.
Step 3: Cost Operator (Penalty Terms)
Quadratic: Apply RZZ(γ * P * wᵢ * wⱼ) on each pair (i,j). This penalizes selecting two heavy items together — the heavier the pair, the stronger the penalty.
Linear: Apply RZ(γ * P * wᵢ * (2C - W)) on each qubit, with W = Σⱼ wⱼ (here 2C - W = 1). This is the Zᵢ coefficient after substituting xᵢ = (1 - Zᵢ)/2 into the whole penalty, cross terms included; the coefficient of xᵢ, P(wᵢ² - 2Cwᵢ), is not the coefficient of Zᵢ. Together with the value gates and the RZZ gates above, this reproduces the QUBO exactly (up to a constant), so the cost layer's lowest-energy subset is {1, 2}, the QUBO minimum, followed by the other optimum {0, 3}. verify_qaoa() checks this for all 16 subsets.
Step 4: Mixer Operator
Apply RX(2β) on each qubit. Same as MaxCut — toggles between including/excluding items to explore neighboring solutions.
Step 5: Measure and Optimize
Measure all qubits → decode item selection → check feasibility → compute value. Classically optimize γ and β to maximize expected value of feasible solutions.
PYTHONfrom circuit import run_circuit, optimize_qaoa # Default parameters result = run_circuit() print(f"Best value: {result['best_value_found']}") print(f"Feasibility rate: {result['feasibility_rate']:.1%}") # Optimize parameters opt = optimize_qaoa(p=1, max_iterations=50, seed=42) print(f"Optimized ratio: {opt['approximation_ratio']:.1%}")
The Math
Cost Hamiltonian
The QUBO objective as a quantum operator:
H_cost = -Σᵢ vᵢ(1 - Zᵢ)/2 + P × (Σᵢ wᵢ(1 - Zᵢ)/2 - C)²
Using the substitution xᵢ = (1 - Zᵢ)/2, the binary variables map to qubit operators. The expanded form has:
- Linear terms → single-qubit RZ rotations
- Quadratic terms → two-qubit RZZ rotations
- Constant terms → global phase (physically irrelevant)
Mixer Hamiltonian
B = Σᵢ Xᵢ
Standard transverse field mixer, identical to MaxCut. Drives transitions between item subsets.
QAOA State
After p layers:
|γ, β⟩ = exp(-iβ_p B) exp(-iγ_p H_cost) ... exp(-iβ₁ B) exp(-iγ₁ H_cost) |+⟩^n
The expected feasible value ⟨γ,β|H_value|γ,β⟩ (restricted to feasible subspace) is maximized over the 2p parameters.
Penalty Parameter P
| P value | Effect |
|---|---|
| P ≪ max(vᵢ) | Constraint violations ignored → infeasible solutions dominate |
| P ≈ max(vᵢ) | Recommended. Balanced trade-off between feasibility and value |
| P ≫ max(vᵢ) | Over-penalizes → the value term is drowned out and the optimizer only tries to hit the weight target |
Rule of thumb: P ≈ max(vᵢ) ensures that violating the constraint is always worse than dropping the most valuable item. This circuit defaults to P = 25 (= max of item values).
Expected Output
| Metric | Value |
|---|---|
| Optimal value (exact) | 35 |
| Optimal items | {1, 2} or {0, 3} (the code reports {1, 2}) |
| Optimal weight | 18 / 18 for {1, 2}; 17 / 18 for {0, 3} |
| QAOA p=1 (default γ = 1.48786, β = 0.547) | An optimal subset in ~53% of samples ({1, 2} 31%, {0, 3} 21%); feasibility ~69%; approximation ratio ~0.87 |
QAOA p=1 (optimize_qaoa, seed 42) | Approximation ratio 0.69 to 0.95 in 54 runs, usually below the defaults; an optimal subset in 1% to 51% of samples at the angles it returns |
| Random baseline | 9/16 subsets feasible, avg feasible value ~21.7 (ratio 0.62); an optimal subset in 2/16 = 12.5% |
These are noiseless simulator results; in runs of 1,024 shots an optimal subset came out in 50% to 55% of samples. The approximation ratio here is the average value of the feasible samples divided by 35, so it ignores infeasible samples. The default angles give the highest probability of sampling an optimal subset on a fine p=1 grid (γ in steps of 0.00002). They are not the angles that minimize the expected QUBO cost: penalty energies reach 8100 (the empty knapsack), so that minimum (γ = 0.565, β = 2.356) mostly avoids heavy penalties and samples an optimal subset less than 1% of the time. The landscape is rugged in γ for the same reason: moving γ by 0.0003 lowers the probability of an optimal subset from 53% to about 30%, and moving it by 0.01 can lower it to 4%. optimize_qaoa maximizes the sampled approximation ratio with COBYLA, and this landscape defeats it: from seed 42 it returns different angles on every run, mostly worse than the defaults.
Running the Circuit
PYTHONfrom circuit import ( run_circuit, optimize_qaoa, verify_qaoa, compute_exact_solution, evaluate_solution, ) # Exact solution exact = compute_exact_solution() print(f"Optimal: value={exact['optimal_value']}, items={exact['optimal_items']}") # QAOA with defaults result = run_circuit(shots=2048) print(f"Best value: {result['best_value_found']}") print(f"Feasibility: {result['feasibility_rate']:.1%}") print(f"Ratio: {result['approximation_ratio']:.1%}") # Optimize opt = optimize_qaoa(p=1, shots=2048, seed=42) print(f"Optimized ratio: {opt['approximation_ratio']:.1%}") # Custom knapsack instance result = run_circuit( values=[5, 10, 15, 20], weights=[2, 4, 6, 8], capacity=10, ) # Evaluate a specific solution sol = evaluate_solution("0110", [10, 15, 20, 25], [5, 8, 10, 12], 18) print(f"Items {sol['items']}: value={sol['value']}, weight={sol['weight']}") # Verification v = verify_qaoa() for check in v["checks"]: print(f"[{'PASS' if check['passed'] else 'FAIL'}] {check['name']}")
Try It Yourself
-
Tune the penalty: Run with
penalty=5(too low) andpenalty=100(too high). How does feasibility rate and best value change? Find the sweet spot. -
Increase p: Run with p=2 (
optimize_qaoa(p=2)). Does the approximation ratio improve? How many more optimizer iterations are needed? -
Greedy comparison: Implement a greedy algorithm (sort by value/weight ratio, pick until full). Compare its solution to QAOA's. For this small instance, does greedy find the optimal?
-
Scale up: Create a 6-item instance and run QAOA. How does the O(n²) RZZ connectivity affect circuit depth? At what point does noise dominate on a real device?
-
Visualize the landscape: Plot expected value as a function of γ ∈ [0, π] and β ∈ [0, π/2] for p=1. Compare the landscape to MaxCut — is it smoother or more rugged?
What's Next
- TSP — QAOA with multi-qubit encoding (permutation constraints)
- Portfolio Optimization: QAOA for financial asset selection (binary selection with a fixed number of assets)
- VQE H₂ Ground State — Another variational algorithm, for quantum chemistry
Applications
| Domain | Use case |
|---|---|
| Resource allocation | Budget planning, project selection under constraints |
| Logistics | Container packing, vehicle loading |
| Supply chain | Inventory optimization with storage limits |
| Finance | Portfolio selection with capital constraints |
| Telecommunications | Bandwidth allocation across channels |
Connection to Resource Allocation
The Knapsack problem is the simplest model of resource allocation under constraints — a pattern that appears across industries. Every time you have a fixed budget (money, weight, time, bandwidth) and a menu of options with different costs and benefits, you're solving a knapsack variant.
The QUBO formulation used here generalizes to multi-constraint problems by adding more penalty terms. Whether QAOA can beat classical solvers on knapsack-type problems at any scale is an open question: classical dynamic programming and branch-and-bound methods already solve large instances.
References
- Lucas, A. (2014). "Ising formulations of many NP problems." Frontiers in Physics 2, 5. DOI: 10.3389/fphy.2014.00005
- Farhi, E., Goldstone, J., Gutmann, S. (2014). "A Quantum Approximate Optimization Algorithm." arXiv: 1411.4028
- Glover, F. et al. (2019). "A Tutorial on Formulating and Using QUBO Models." arXiv: 1811.11538