Dynamic Programming21 sections · 916 units
Open in Course

Codeforces 977F Consecutive Subsequence - Final Answer and Reconstruction

Learn how to find the answer and rebuild the subsequence

The final answer is max(dp[i])\max(dp[i]) over all positions, since the longest sequence can end anywhere. To reconstruct the subsequence: track prev[i]prev[i] for each index.

This records where the sequence jumped from. Start at best_endbest\_end (the index with max dpdp value), follow prevprev pointers backward, then reverse. Example: if prev=[1,0,1,1,3]prev = [-1, 0, 1, -1, 3] and best_end=4best\_end = 4, follow 4314 \to 3 \to -1. Collect [4,3][4, 3], reverse to get [3,4][3, 4].