0
0
DSA Typescriptprogramming~10 mins

Unbounded Knapsack Problem in DSA Typescript - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to initialize the dp array with zeros.

DSA Typescript
const dp: number[] = new Array([1] + 1).fill(0);
Drag options to blanks, or click blank then click option'
Acapacity
Bweights.length
Cvalues.length
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using the number of items instead of capacity for dp size.
Not adding 1 to capacity for dp array length.
2fill in blank
medium

Complete the code to iterate over all capacities from 1 to capacity.

DSA Typescript
for (let cap = 1; cap <= [1]; cap++) {
Drag options to blanks, or click blank then click option'
Avalues.length
Bcapacity
Cweights.length
Ddp.length
Attempts:
3 left
💡 Hint
Common Mistakes
Using dp.length which is capacity + 1, causing off-by-one errors.
Using number of items instead of capacity.
3fill in blank
hard

Fix the error in the condition to check if the current item can fit in the current capacity.

DSA Typescript
if (weights[i] [1] cap) {
Drag options to blanks, or click blank then click option'
A<=
B>
C==
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using > which is the opposite condition.
Using == which misses items that are lighter than capacity.
4fill in blank
hard

Fill both blanks to update dp[cap] with the maximum value including the current item.

DSA Typescript
dp[cap] = Math.max(dp[cap], dp[cap - [1]] + [2]);
Drag options to blanks, or click blank then click option'
Aweights[i]
Bvalues[i]
Ccap
Di
Attempts:
3 left
💡 Hint
Common Mistakes
Using cap instead of weights[i] for subtraction.
Adding weights[i] instead of values[i].
5fill in blank
hard

Fill all three blanks to complete the unbounded knapsack function.

DSA Typescript
function unboundedKnapsack([1]: number[], [2]: number, [3]: number[]): number {
  const dp: number[] = new Array([2] + 1).fill(0);
  for (let cap = 1; cap <= [2]; cap++) {
    for (let i = 0; i < [1].length; i++) {
      if ([1][i] <= cap) {
        dp[cap] = Math.max(dp[cap], dp[cap - [1][i]] + [3][i]);
      }
    }
  }
  return dp[[2]];
}
Drag options to blanks, or click blank then click option'
Aweights
Bcapacity
Cvalues
Ditems
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up weights and values parameter order.
Using incorrect variable names inside the function.