ProgrammingHardAccenture · Cognizant
Array a = [2,3,1,1,4,2,1,3,1,1] (0-based). From index i you may jump forward at most a[i] positions. Starting at index 0, the greedy below counts the minimum number of jumps to reach the last index. What is printed?
Array a = [2,3,1,1,4,2,1,3,1,1] (0-based). From index i you may jump forward at most a[i] positions. Starting at index 0, the greedy below counts the minimum number of jumps to reach the last index. What is printed?
n = 10; jumps = 0; end = 0; far = 0
for i = 0 to n - 2
far = max(far, i + a[i])
if i == end then jumps = jumps + 1; end = far
end for
Print jumps- A. 5
- B. 9
- C. 1
- D. 4
Correct answer: D. 4
The farthest reachable index is extended in each window, and a jump is counted when the current window ends. Following only the first index of the array in each step, counting loop iterations, and updating the window before extending it each give different counts.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Tasks with the same letter must be separated by at least n = 2 idle or other slots. The task string is AAABBC. The greedy formula below…
- Items of sizes 5, 7, 5, 2, 4, 2, 5, 1, 6 are packed in this order into bins of capacity 10 using the first-fit rule: put each item into…
- Coins are 1, 5, 10, 21 and 25. To pay 63, the greedy method below always takes the largest coin that fits, using the list in descending…
- Intervals (start, end): (1,10), (2,3), (4,5), (6,7), (8,9). The greedy below selects the largest set of pairwise disjoint intervals…
- Each event is (time, +1) for a train arriving or (time, -1) for a train departing. Arrivals are at 1, 3, 3, 5, 6, 8 and departures are at…
- Five numbers 3, 30, 34, 5, 9 are to be arranged to form the largest possible number. Two numbers x, y are put in the order that gives the…