Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
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.
✗ Incorrect
We create a dp array of size capacity + 1 to store maximum values for each capacity from 0 to capacity.
2fill in blank
mediumComplete 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'
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.
✗ Incorrect
We loop from 1 to capacity to fill dp for all capacities.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using > which is the opposite condition.
Using == which misses items that are lighter than capacity.
✗ Incorrect
We check if the item's weight is less than or equal to the current capacity to decide if it fits.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using cap instead of weights[i] for subtraction.
Adding weights[i] instead of values[i].
✗ Incorrect
We subtract the item's weight from capacity and add its value to find the new max value.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up weights and values parameter order.
Using incorrect variable names inside the function.
✗ Incorrect
The function takes weights, capacity, and values arrays to compute the maximum value for unbounded knapsack.