After loop, maxVal is 13, but code prints maxVal after loop ends. The code prints 13.
Final Answer:
13 -> Option A
Quick Check:
Max profit for length 4 = 13 [OK]
Hint: Check all splits and sum prices to find max [OK]
Common Mistakes:
Not considering all splits i=1 to n
Off-by-one errors in array indexing
Printing maxVal before loop ends
4. Identify the error in this Java method for rod cutting:
public int cutRod(int[] price, int n) {
if (n <= 0) return 0;
int maxVal = Integer.MIN_VALUE;
for (int i = 1; i < n; i++) {
maxVal = Math.max(maxVal, price[i-1] + cutRod(price, n - i));
}
return maxVal;
}
medium
A. Recursive call parameters are incorrect
B. Base case should return 1 instead of 0
C. Loop should run from i = 1 to i <= n
D. maxVal should be initialized to 0 instead of Integer.MIN_VALUE
Solution
Step 1: Analyze the loop range
The loop runs from i=1 to i<n, so it misses the case i=n which is needed to consider the whole rod as one piece.
Step 2: Correct the loop condition
The loop should run from i=1 to i<=n to include all possible cuts including the full length.
Final Answer:
Loop should run from i = 1 to i <= n -> Option C
Quick Check:
Include full length cut by looping to i <= n [OK]
Hint: Loop must include full rod length i = n [OK]
Common Mistakes:
Using i < n instead of i <= n
Incorrect base case return value
Wrong initialization of maxVal
5. Given a rod of length 5 and price array int[] price = {2, 5, 7, 8, 10};, what is the maximum profit using dynamic programming approach?
hard
A. 14
B. 10
C. 15
D. 12
Solution
Step 1: Calculate max profit for each length up to 5
Length 1: max = 2 Length 2: max = max(5, 2+2=4) = 5 Length 3: max = max(7, 5+2=7, 2+5=7) = 7 Length 4: max = max(8, 7+2=9, 5+5=10, 2+7=9) = 10 Length 5: max = max(10, 10+2=12, 7+5=12, 5+7=12, 2+10=12) = 12
Step 2: Check if cutting into smaller pieces yields better profit
Try cutting length 5 into 1+4, 2+3, 3+2, 4+1 etc. The best is 2+3 or 3+2 or 1+4 giving 12, but also check if full length price 10 is less than these.
Step 3: Recalculate carefully
Check all splits: 1+4: 2 + 10 = 12 2+3: 5 + 7 = 12 3+2: 7 + 5 = 12 4+1: 8 + 2 = 10 But also check if cutting into 1+1+3 or 1+1+1+2 etc. can yield more. Try 1+1+3: 2+2+7=11 Try 1+1+1+2: 2+2+2+5=11 Try 1+1+1+1+1: 2*5=10 So max is 12.
Final Answer:
12 -> Option D
Quick Check:
Max profit for length 5 = 12 [OK]
Hint: Check all splits and pick max sum for length 5 [OK]
Common Mistakes:
Choosing price of full length only
Not checking all split combinations
Confusing price array indices
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.