DryRun
AlgorithmsCourseCompare
DryRun
AlgorithmsCourseCompareGitHubLinkedIn

© 2026 DryRun. Built by Aditya Pandey.

AlgorithmsAdvanced0/1 Knapsack (Branch and Bound)
Advancedadvancedbranch-and-boundknapsackstate-space-tree

0/1 Knapsack (Branch and Bound)

Branch and Bound explores include/exclude decisions for each item while computing an optimistic upper bound using fractional knapsack logic. Nodes whose bound is below current best are pruned.

Complexity

Best
O(2^n)
Average
O(2^n)
Worst
O(2^n)
Space
O(n)

Implementation

struct Item { int w, v; double r; };
struct Node { int lvl, w, val; double bound; };
double ubound(Node u, int W, vector<Item>& a) {
    if (u.w >= W) return 0;
    double profit = u.val;
    int j = u.lvl + 1, tw = u.w;
    while (j < (int)a.size() && tw + a[j].w <= W) { tw += a[j].w; profit += a[j].v; j++; }
    if (j < (int)a.size()) profit += (W - tw) * a[j].r;
    return profit;
}

How It Works

1.Node Bound

Upper bound estimates the best possible value below a node.

2.Pruning Rule

If bound <= current best, subtree cannot improve answer and is discarded.

3.Ordering

Sorting by value/weight improves pruning quality.

Related Algorithms

LayoutGrid0/1 KnapsackTrendingUpFractional Knapsack

Test Your Knowledge

Quiz coming soon for this algorithm.

Back to all algorithms