Problem Statement in English
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.
Note that when you are reach a magician, you must take energy from them, whether it is negative or positive energy.
Approach
We can use a DP to solve this since there are overlapping subproblems.
However, we must ensure that we make it a one dimensional DP, and not a two dimensional DP, since the constraints are large (up to $10^5$).
Solution in Python
class Solution:
def maximumEnergy(self, energy: List[int], k: int) -> int:
res = energy[-1]
@cache
def dfs(i):
nonlocal res
if i >= len(energy):
return 0
else:
temp = energy[i] + dfs(i + k)
res = max(res, temp)
return temp
for i in range(len(energy)):
dfs(i)
return res
Complexity
Time: $O(n)$
Since we are calculating the result for $n$ subproblems.Space: $O(n)$
Since we are using a cache to store results of $n$ subproblems.
And we are done.