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.
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.
classSolution {
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
classSolution {
publicintmaximumEnergy(int[] energy, int k) {
int n = energy.length;
int[] dp =newint[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
classSolution {
funmaximumEnergy(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
classSolution:
defmaximumEnergy(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
pubfnmaximum_energy(energy: Vec<i32>, k: i32) -> i32 {
let n = energy.len();
let k = k asusize;
letmut dp =vec![0; n];
letmut 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
}