[LeetCode] Taking Maximum Energy From the Mystic Dungeon

3147. Taking Maximum Energy From the Mystic Dungeon

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int maximumEnergy(vector<int>& energy, int k) {
int res = INT_MIN;
vector<int> dp(energy.size());
for(int i = energy.size()-1; i >= 0; i--) {
dp[i] += energy[i];
if(i + k < energy.size()) dp[i] += dp[i+k];
res = max(res, dp[i]);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/05/12/PS/LeetCode/taking-maximum-energy-from-the-mystic-dungeon/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.