#1 India's Top IT Training Institute

×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Dynamic Programming

0/1 Knapsack Problem

The 0/1 Knapsack problem asks: given a set of items, each with a weight and a value, and a knapsack with a maximum weight capacity, determine the maximum total value that can be carried, where each item can either be fully included or excluded (no fractional items).

Recursive Approach

At every item, decide to either include it (if it fits) or skip it, and take the maximum of both choices. This naive recursion recomputes overlapping subproblems and runs in exponential time.

Dynamic Programming Approach

Build a table dp[i][w] representing the maximum value achievable using the first i items with capacity w. Each cell is computed from smaller subproblems, avoiding recomputation.

def knapsack(weights, values, capacity):
    n = len(weights)
    dp = [[0] * (capacity + 1) for _ in range(n + 1)]

    for i in range(1, n + 1):
        for w in range(capacity + 1):
            if weights[i - 1] <= w:
                dp[i][w] = max(dp[i - 1][w],
                                dp[i - 1][w - weights[i - 1]] + values[i - 1])
            else:
                dp[i][w] = dp[i - 1][w]

    return dp[n][capacity]

print(knapsack([1, 3, 4, 5], [1, 4, 5, 7], 7))  # Output: 9

Complexity

ApproachTimeSpace
Naive RecursionO(2^n)O(n)
Dynamic ProgrammingO(n * capacity)O(n * capacity)

Applications

  • Resource allocation and budgeting problems.
  • Cargo loading and shipment optimization.
  • Portfolio selection under a fixed investment budget.

Ready to master Data Structures & Algorithms?

Learn DSA hands-on with mentor-led sessions, real interview practice, and placement support.

Explore Course