computeS(X)
for to
if
end if
end for
return S
Which ONE of the following values is returned by the function computeS(X)
for X = [6, 3, 5, 4, 10]?
C
Step-by-Step Solution
Insight: This is a consecutive sequence DP question where S[i] represents the length of the longest non-decreasing contiguous subarray ending at index i. The pseudocode implements the standard "extend or reset" pattern.
Exam route: Trace the pseudocode step by step for the given array X = [6, 3, 5, 4, 10].
Learning route:
- i=1: S[1] = 1 (base case, single element is always valid).
- i=2: X[1]=6, X[2]=3. Check 6 <= 3: false. So S[2] remains 1 (reset).
- i=3: X[2]=3, X[3]=5. Check 3 <= 5: true. So S[3] = 1 + S[2] = 1 + 1 = 2 (extend).
- i=4: X[3]=5, X[4]=4. Check 5 <= 4: false. So S[4] remains 1 (reset).
- i=5: X[4]=4, X[5]=10. Check 4 <= 10: true. So S[5] = 1 + S[4] = 1 + 1 = 2 (extend).
Final array: S = [1, 1, 2, 1, 2].
Verification: The longest non-decreasing contiguous subarrays ending at each index are: [6] (length 1), [3] (length 1), [3, 5] (length 2), [4] (length 1), [4, 10] (length 2). This matches S = [1, 1, 2, 1, 2].