Taking Maximum Energy From the Mystic Dungeon - Problem

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 reach a magician, you must take energy from them, whether it is negative or positive energy.

Input & Output

Example 1 — Basic Case
$ Input: energy = [5,2,-3,1,-4], k = 2
Output: 3
💡 Note: Starting from position 1: visit positions 1→3, collecting energy 2+1 = 3. This is better than starting from position 0 (5+(-3)+(-4) = -2) or position 2 ((-3)+(-4) = -7).
Example 2 — All Negative
$ Input: energy = [-2,-3,-1], k = 2
Output: -1
💡 Note: Starting from position 2: only visit position 2, collecting energy -1. Starting from position 0: visit 0→2, collecting -2+(-1) = -3. Starting from position 1: only visit position 1, collecting -3.
Example 3 — Large Jump
$ Input: energy = [1,2,3,4,5], k = 10
Output: 5
💡 Note: Since k=10 is larger than the array length, we can only visit one position. The maximum energy is 5 from position 4.

Constraints

  • 1 ≤ energy.length ≤ 104
  • 1 ≤ k ≤ energy.length
  • -1000 ≤ energy[i] ≤ 1000

Visualization

Tap to expand
Mystic Dungeon: Choose Starting Position and Jump k=2 Steps52-31-401234Start HereJump k=2Path: Start at position 1 → Jump to position 3Energy collected: 2 + 1 = 3Maximum Energy: 3
Understanding the Visualization
1
Input
Array of energy values and jump distance k
2
Process
Try different starting positions, jumping k steps each time
3
Output
Maximum energy possible from any valid path
Key Takeaway
🎯 Key Insight: Each starting position creates a unique sequence with k-step jumps - find the sequence that maximizes total energy
Asked in
Amazon 35 Microsoft 28
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen