3383. Taking Maximum Energy From The Mystic Dungeon¶
Difficulty: Medium
LeetCode Problem View on GitHub
3383. Taking Maximum Energy From the Mystic Dungeon
Medium
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.
Example 1:
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:
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 <= 105-1000 <= energy[i] <= 10001 <= k <= energy.length - 1
​​​​​​
Solution¶
class Solution {
private int dp[][];
public int maximumEnergy(int[] arr, int k) {
int n = arr.length;
dp = new int[n + 1][2];
for (int current[] : dp)
Arrays.fill(current, (int)(-1e9));
return solve(0, arr, 0, k);
}
private int solve(int idx, int arr[], int taken, int k) {
if (idx >= arr.length) {
if (taken == 0) {
return Integer.MIN_VALUE;
}
return 0;
}
if (dp[idx][taken] != (int)(-1e9))
return dp[idx][taken];
if (taken == 0) {
int op1 = arr[idx] + solve(idx + k, arr, 1, k);
int op2 = solve(idx + 1, arr, 0, k);
return dp[idx][taken] = Math.max(op1, op2);
} else {
return dp[idx][taken] = arr[idx] + solve(idx + k, arr, 1, k);
}
}
}
Complexity Analysis¶
- Time Complexity:
O(?) - Space Complexity:
O(?)
Approach¶
Detailed explanation of the approach will be added here