ProgrammingHardInfosys · Cognizant
The array a = [2, 3, 4, 1, 2, 3, 9] is scanned for its longest run of consecutive positions where each element is exactly one more than the previous element. The procedure below prints the length of the longest such run. What is printed?
The array a = [2, 3, 4, 1, 2, 3, 9] is scanned for its longest run of consecutive positions where each element is exactly one more than the previous element. The procedure below prints the length of the longest such run. What is printed?
best = 1; run = 1
for i = 1 to n - 1
if a[i] == a[i-1] + 1 then run = run + 1 else run = 1
best = max(best, run)
end for
Print best- A. 4
- B. 3
- C. 5
- D. 1
Correct answer: B. 3
The runs 2, 3, 4 and 1, 2, 3 each have length 3, so the answer is 3. Accepting any rise gives 4 (the final 3, 9 also counts), counting distinct values gives 5, and accepting only steps of minus one gives 1 here.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- The stack-based procedure below computes, for each index i of a = [4, 2, 6, 1, 5], the index of the next greater element to its right (or…
- An array a = [1, 3, 5, 7, 9, 11, 13, 15] is searched with binary search for the target 15, and the procedure counts how many array…
- The procedure below converts the Roman numeral "MCMXCIV" to a number by reading left to right and subtracting a symbol's value when the…
- A recursive function is written as below. The procedure counts the calls made for input 7, including the first call. What is printed?…
- The procedure below uses exponentiation by squaring on the exponent 37. It counts one multiplication into result each time the current…
- Recursive merge sort splits an array of length n into halves of length n div 2 and n minus n div 2, and calls itself on each half unless…