LeetCode Challenge Day 25 β 3147. Taking Maximum Energy From the Mystic Dungeon
Nitin Ahirwal / October 10, 2025
Hey folks
This is Day 25 of my LeetCode streak π.
Todayβs problem is 3147. Taking Maximum Energy From the Mystic Dungeon β a dynamic programming style problem where magicians can either give or take away energy, and you jump in fixed steps of k.
π Problem Statement
You are given:
-
energy[i]β the energy value of the i-th magician (can be positive or negative). -
An integer
k.
Rules:
-
Start from any magician.
-
After absorbing their energy, you are instantly transported to magician
(i + k). -
This continues until you jump out of bounds.
Return the maximum possible energy you can gain.
Examples
-
Input:
energy = [5,2,-10,-5,1], k = 3
Output:
3 -
Input:
energy = [-2,-3,-1], k = 2
Output:
-1
π‘ Intuition
The magicians can be partitioned into k independent subsequences.
From any starting index i, the path is fixed:
i β i+k β i+2k β ... until going out of bounds.
Thus, the problem reduces to calculating the sum for each possible subsequence and picking the maximum.
π Approach
-
Define
dp[i]as the maximum energy we can collect starting at magiciani. -
Transition:
dp[i] = energy[i] + (dp[i+k] if i+k < n else 0) -
Process magicians in reverse (from
n-1to0) to ensure future states are already computed. -
Track the maximum of all
dp[i]values as the final answer.
β±οΈ Complexity Analysis
-
Time complexity:
O(n)β each magician is processed once. -
Space complexity:
O(n)β for the DP array (can be optimized to O(1), but O(n) works fine here).
π§βπ» Code (JavaScript)
/**
* @param {number[]} energy
* @param {number} k
* @return {number}
*/
var maximumEnergy = function(energy, k) {
let n = energy.length;
let dp = Array(n).fill(0);
let maxEnergy = -Infinity;
for (let i = n - 1; i >= 0; i--) {
dp[i] = energy[i];
if (i + k < n) {
dp[i] += dp[i + k];
}
maxEnergy = Math.max(maxEnergy, dp[i]);
}
return maxEnergy;
};
π§ͺ Edge Cases
-
All energies negative β best choice is the least negative magician.
-
k = 1β must absorb all energies in order. -
k = n-1β can only choose between at most two starting magicians.
π₯ Reflections
This problem is a neat example of reducing a teleporting/jump simulation into a DP formulation.
-
Breaking the problem into subsequences makes it easy.
-
The bottom-up DP ensures efficiency.
Thatβs it for Day 25 of my LeetCode journey!
On to the next challenge π₯
Happy Coding π¨βπ»