Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to initialize the maximum revenue array with zeros.
DSA Javascript
const maxRevenue = new Array(n + 1).fill([1]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using undefined or null instead of 0 causes errors when calculating max revenue.
✗ Incorrect
We fill the array with 0 because initially, the maximum revenue for all lengths is zero.
2fill in blank
mediumComplete the code to loop through all possible first cut lengths.
DSA Javascript
for (let i = 1; i <= [1]; i++) {
Attempts:
3 left
💡 Hint
Common Mistakes
Using price.length causes errors if price array length differs from n.
✗ Incorrect
We loop from 1 to n because the rod length is n and we consider all cut lengths.
3fill in blank
hardFix the error in updating the maximum revenue inside the loop.
DSA Javascript
maxRevenue[j] = Math.max(maxRevenue[j], price[i - 1] + maxRevenue[j - [1]]);
Attempts:
3 left
💡 Hint
Common Mistakes
Using j or 1 instead of i causes wrong indexing and incorrect revenue calculation.
✗ Incorrect
We subtract i because i is the length of the first cut, so the remaining length is j - i.
4fill in blank
hardFill both blanks to complete the nested loop for calculating max revenue.
DSA Javascript
for (let j = [1]; j <= n; j++) { maxRevenue[j] = Math.max(maxRevenue[j], price[i - 1] + maxRevenue[j - [2]]); }
Attempts:
3 left
💡 Hint
Common Mistakes
Starting j from 1 or 0 causes index errors or incorrect calculations.
✗ Incorrect
The inner loop starts from i because we cannot cut a piece longer than the current length i, and we subtract i to get the remaining length.
5fill in blank
hardFill all three blanks to complete the function that returns the maximum revenue for rod length n.
DSA Javascript
function rodCutting(price, n) {
const maxRevenue = new Array(n + 1).fill(0);
for (let i = [1]; i <= n; i++) {
for (let j = [2]; j <= n; j++) {
maxRevenue[j] = Math.max(maxRevenue[j], price[i - 1] + maxRevenue[j - [3]]);
}
}
return maxRevenue[n];
}Attempts:
3 left
💡 Hint
Common Mistakes
Starting loops at 0 or subtracting wrong variables causes errors.
✗ Incorrect
The outer loop starts at 1, the inner loop starts at i, and we subtract i to get the remaining length after the cut.
