2. Given the following code snippet implementing the optimal candy distribution algorithm, what is the final returned value when input ratings = [1, 0, 2]?
Returning -1 signals no solution; 0 misleads caller [OK]
Hint: Return -1 on failure, not 0 [OK]
Common Mistakes:
Returning 0 instead of -1 on failure
Overcounting rotations when both sides equal candidate
5. Suppose the problem is modified: instead of finding the largest monotone increasing digits number ≤ n, you want the largest monotone increasing digits number ≤ n that can reuse digits any number of times (digits can be repeated arbitrarily). Which approach correctly adapts the algorithm?
hard
A. Use the original greedy algorithm but allow digits after marker to be any digit less than or equal to the digit at marker-1
B. Sort the digits of n and build the largest monotone number by repeating the smallest digit as many times as needed
C. Use a backtracking approach to generate all monotone numbers with digits ≤ those in n, allowing reuse, and pick the largest ≤ n
D. Modify the greedy algorithm to decrement digits and set trailing digits to the digit at marker-1 instead of 9
Solution
Step 1: Understand digit reuse changes problem nature
Allowing reuse means digits can be repeated arbitrarily, so greedy digit decrement and trailing 9 assignment no longer guarantee largest monotone number ≤ n.
Step 2: Backtracking enumerates all monotone numbers with digit reuse
Backtracking can generate all monotone numbers with digits ≤ those in n, allowing reuse, then pick the largest ≤ n.
Step 3: Other options fail to handle reuse or produce incorrect numbers
Sorting digits or modifying trailing digits to marker-1 digit does not guarantee largest monotone number with reuse.
Final Answer:
Option C -> Option C
Quick Check:
Backtracking correctly handles reuse and monotonicity constraints [OK]
Hint: Digit reuse breaks greedy; backtracking needed for correctness [OK]
Common Mistakes:
Trying to adapt greedy without full enumeration
Assuming trailing digits can be set to 9 or marker digit