Editorial

# 1. Problem Understanding We are given a sequence of $N$ stones numbered from $1$ to $N$, where each stone $i$ has an associated magic value $A_i$. A wanderer starts at stone $1$ and must reach stone $N$ while collecting magic values from the stones he lands on. However, the wanderer is allowed to jump only forward, and from stone $i$, he can jump to any stone $j$ such that $$i < j \leq i + K,$$ where $K$ is the maximum jump length. The goal is to maximize the total magic points collected on the journey from stone $1$ to stone $N$. This is a typical optimization problem under a limited jump constraint and it has overlapping subproblems, which often suggests a dynamic programming approach. # 2. Solution Analysis To solve the problem, we can use Dynamic Programming (DP). We define a DP table (or an array) where $dp[i]$ represents the maximum total magic points collectable when reaching stone $i$. The recurrence is based on the idea that to calculate $dp[i]$ for any stone $i$, one only needs to look at the previous $K$ stones from which stone $i$ could be reached. The transition is as follows: $$dp[i] = A_i + \max(dp[i-1], dp[i-2], \dots, dp[i-K]),$$ where the maximum is taken over all valid indices (ensuring $i - k \geq 1$). The reason this works is that if the wanderer jumps from a previous stone $j$ to stone $i$, the best possible score at stone $j$ is $$dp[j]$$, and from there we add the magic value of stone $i$, i.e., $A_i$. The process begins with initializing $dp[1]$ (or index $0$ if using 0-based indexing) to the magic value on stone $1$. We then iteratively compute the maximum achievable score for each stone until we reach stone $N$. # 3. Time and Space Complexity Analysis The overall complexity of the solution depends on how we compute the maximum among the last $K$ DP values for each stone. - If we compute the maximum by scanning the previous $K$ indices for each stone, the worst-case time complexity becomes $O(N \times K)$. - There are possible optimizations (for instance, using data structures like a deque to maintain a sliding window maximum) to achieve $O(N)$ time complexity. Space complexity is $O(N)$ as we are storing a DP array of size $N$. In the optimized version, additional space for the data structure (deque) is at most $O(K)$, which is bounded by $O(N)$.

Author's Solution

GNU C++17