Problem

In a mystic dungeon, n magicians are standing in a line. Each magician has an attribute that gives you energy. Some magicians can give you negative energy, which means taking energy from you.

You have been cursed in such a way that after absorbing energy from magician i, you will be instantly transported to magician (i + k). This process will be repeated until you reach the magician where (i + k) does not exist.

In other words, you will choose a starting point and then teleport with k jumps until you reach the end of the magicians’ sequence, absorbing all the energy during the journey.

You are given an array energy and an integer k. Return the maximum possible energy you can gain.

Examples

Example 1

1
2
3
4
5
6
7

Input: energy = [5,2,-10,-5,1], k = 3

Output: 3

Explanation: We can gain a total energy of 3 by starting from magician 1
absorbing 2 + 1 = 3.

Example 2

1
2
3
4
5
6

Input: energy = [-2,-3,-1], k = 2

Output: -1

Explanation: We can gain a total energy of -1 by starting from magician 2.

Constraints

  • 1 <= energy.length <= 10^5
  • -1000 <= energy[i] <= 1000
  • 1 <= k <= energy.length - 1

Solution

Method 1 - DP by k-step Summation

Intuition

Indices visited from any starting index i are exactly i, i+k, i+2k, .... Each such arithmetic subsequence’s total energy is independent of other starting indices. If we compute for every index the total energy collected when starting there and jumping by k, the answer is the maximum among these totals. Computing these totals from the end reuses previously computed values and yields an O(n) DP.

Approach

Let dp[i] be the total energy gained if you start at index i and repeatedly jump by k until you exit the array. Then:

1
dp[i] = energy[i] + (i + k < n ? dp[i + k] : 0)

Compute dp in decreasing index order (from n-1 down to 0) so that dp[i+k] is already available. Track the maximum dp[i] while computing.

This preserves the original function signatures used in the repo; language-specific wrappers (classes) are only added where a language requires it.

Code

1
2

##### C++
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
public:
    int maximumEnergy(vector<int>& energy, int k) {
        int n = energy.size();
        vector<int> dp(n);
        int ans = INT_MIN;
        for (int i = n - 1; i >= 0; --i) {
            if (i + k < n)
                dp[i] = energy[i] + dp[i + k];
            else
                dp[i] = energy[i];
            ans = max(ans, dp[i]);
        }
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
    public int maximumEnergy(int[] energy, int k) {
        int n = energy.length;
        int[] dp = new int[n];
        int ans = Integer.MIN_VALUE;
        for (int i = n - 1; i >= 0; --i) {
            if (i + k < n) {
                dp[i] = energy[i] + dp[i + k];
            } else {
                dp[i] = energy[i];
            }
            ans = Math.max(ans, dp[i]);
        }
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
    fun maximumEnergy(energy: IntArray, k: Int): Int {
        val n = energy.size
        val dp = IntArray(n)
        var ans = Int.MIN_VALUE
        for (i in n - 1 downTo 0) {
            dp[i] = energy[i]
            if (i + k < n) dp[i] += dp[i + k]
            ans = maxOf(ans, dp[i])
        }
        return ans
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
    def maximumEnergy(self, energy: list[int], k: int) -> int:
        n = len(energy)
        dp = [0] * n
        ans = float('-inf')
        for i in range(n-1, -1, -1):
            if i + k < n:
                dp[i] = energy[i] + dp[i + k]
            else:
                dp[i] = energy[i]
            ans = max(ans, dp[i])
        return ans
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
pub fn maximum_energy(energy: Vec<i32>, k: i32) -> i32 {
    let n = energy.len();
    let k = k as usize;
    let mut dp = vec![0; n];
    let mut ans = i32::MIN;
    for i in (0..n).rev() {
        dp[i] = energy[i];
        if i + k < n {
            dp[i] += dp[i + k];
        }
        ans = ans.max(dp[i]);
    }
    ans
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function maximumEnergy(energy: number[], k: number): number {
    const n = energy.length;
    const dp = new Array(n).fill(0);
    let ans = -Infinity;
    for (let i = n - 1; i >= 0; --i) {
        dp[i] = energy[i];
        if (i + k < n) dp[i] += dp[i + k];
        ans = Math.max(ans, dp[i]);
    }
    return ans;
}

Complexity

  • ⏰ Time complexity: O(n) – we visit each index once and perform O(1) work per index.
  • 🧺 Space complexity: O(n) – the dp array of length n stores intermediate sums.