Editorial

Forests of Fangorn

1. Problem Understanding

We are given a sequence of NN stones numbered from 11 to NN, where each stone ii has an associated magic value AiA_i. A wanderer starts at stone 11 and must reach stone NN while collecting magic values from the stones he lands on. However, the wanderer is allowed to jump only forward, and from stone ii, he can jump to any stone jj such that i<ji+K,i < j \leq i + K, where KK is the maximum jump length. The goal is to maximize the total magic points collected on the journey from stone 11 to stone NN. 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]dp[i] represents the maximum total magic points collectable when reaching stone ii. The recurrence is based on the idea that to calculate dp[i]dp[i] for any stone ii, one only needs to look at the previous KK stones from which stone ii could be reached. The transition is as follows:

dp[i]=Ai+max(dp[i1],dp[i2],,dp[iK]),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 ik1i - k \geq 1). The reason this works is that if the wanderer jumps from a previous stone jj to stone ii, the best possible score at stone jj is dp[j]dp[j], and from there we add the magic value of stone ii, i.e., AiA_i.

The process begins with initializing dp[1]dp[1] (or index 00 if using 0-based indexing) to the magic value on stone 11. We then iteratively compute the maximum achievable score for each stone until we reach stone NN.

3. Time and Space Complexity Analysis

The overall complexity of the solution depends on how we compute the maximum among the last KK DP values for each stone.

  • If we compute the maximum by scanning the previous KK indices for each stone, the worst-case time complexity becomes O(N×K)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)O(N) time complexity.

Space complexity is O(N)O(N) as we are storing a DP array of size NN. In the optimized version, additional space for the data structure (deque) is at most O(K)O(K), which is bounded by O(N)O(N).

Author's Solution

GNU C++23