FastPrep0/1 Knapsack: Best Value Within a Weight Limit
Problems/0/1 Knapsack: Best Value Within a Weight Limit

0/1 Knapsack: Best Value Within a Weight Limit

Adobe logoAdobe● MediumFULLTIMEPHONE SCREEN
QuestionFunctionExamplesConstraints

Problem statement

Source note: In the first round (DSA) of an Adobe MTS-2 interview loop, one of the two coding items is reported only as a knapsack problem that differed a little from the textbook version; the change is never described. The candidate's answer used a two-dimensional table and then reduced it.

The report does not describe the variation, the limits or examples. So this version is the classic 0/1 knapsack: each item at most once, total weight within the capacity, largest total value. There are at most 100 items, weights 1 to 1000, values 0 to 10^4 and capacity 0 to 10^4. The examples are our own.

The judged task matches the report at about 70%.

You have n items. Item i weighs weights[i] and is worth values[i]. Your bag can carry a total weight of at most capacity.

Choose a set of items whose total weight is at most capacity and whose total value is as large as possible. Each item can be taken at most once, and items cannot be split. Return the largest total value (0 if nothing fits).

Function

maxKnapsackValue(weights: int[], values: int[], capacity: int) → int

Examples

Example 1

weights = [3,4,5]values = [30,50,60]capacity = 8return = 90

The weights 3 and 5 fill the capacity of 8 exactly and are worth 30 + 60 = 90. Other choices are worth less: 3 and 4 give 80, and 4 alone or 5 alone give 50 or 60. All three items weigh 12, which is too much.

Example 2

weights = [2,9]values = [7,7]capacity = 0return = 0

With capacity 0 nothing fits, so the best value is 0.

Example 3

weights = [5]values = [10]capacity = 4return = 0

The only item weighs 5, more than the capacity 4, so nothing can be taken.

Constraints

  • 1 <= weights.length <= 100 and values.length == weights.length
  • 1 <= weights[i] <= 1000
  • 0 <= values[i] <= 10^4
  • 0 <= capacity <= 10^4

More Adobe problems

  • Evaluate a Parenthesized Integer ExpressionPHONE SCREEN · Seen Oct 2026
  • All Elements of Two BSTs in OrderPHONE SCREEN · Seen Aug 2026
  • Rotate an Array In PlaceOA · PHONE SCREEN · Seen Aug 2026
All Adobe interview questionsSee Adobe hiring insights
Saved
public int maxKnapsackValue(int[] weights, int[] values, int capacity) {
    // Write your code here.
}
Checking account…