Taking Maximum Energy From the Mystic Dungeon - Problem

In a mystical dungeon, n magicians stand in a line, each possessing unique magical energy that can either boost your power or drain your strength. You've been cursed with a teleportation spell that forces you to jump exactly k positions after absorbing energy from each magician.

Here's how it works:

  • Choose any starting position i
  • Absorb the magician's energy (positive or negative)
  • Teleport to position i + k
  • Repeat until you can't jump anymore (when i + k โ‰ฅ n)

Goal: Find the starting position that gives you the maximum total energy possible.

Example: With energy = [5, 2, -3, 1, -4] and k = 2, starting at index 0 gives you: 5 + (-3) + (-4) = -2, while starting at index 1 gives you: 2 + 1 = 3.

Input & Output

example_1.py โ€” Basic Case
$ Input: energy = [5, 2, -3, 1, -4], k = 2
โ€บ Output: 3
๐Ÿ’ก Note: Starting at index 1: 2 โ†’ 1 (sum = 3). Starting at index 0: 5 โ†’ -3 โ†’ -4 (sum = -2). The maximum is 3.
example_2.py โ€” All Positive
$ Input: energy = [1, 2, 3, 4], k = 1
โ€บ Output: 10
๐Ÿ’ก Note: With k=1, we visit every element in sequence. Starting from any position gives us the sum of all elements: 1+2+3+4 = 10.
example_3.py โ€” Large Jump
$ Input: energy = [5, -2, -3], k = 3
โ€บ Output: 5
๐Ÿ’ก Note: Starting at index 0: only visit 5 (no more jumps possible). Starting at index 1: only visit -2. Starting at index 2: only visit -3. Maximum is 5.

Constraints

  • 1 โ‰ค n โ‰ค 104
  • 1 โ‰ค k โ‰ค n
  • -1000 โ‰ค energy[i] โ‰ค 1000
  • You must absorb energy from every magician you visit

Visualization

Tap to expand
๐Ÿฐ Mystic Dungeon Energy Collection+5Pos 0+2Pos 1-3Pos 2+1Pos 3-4Pos 4๐Ÿ‘ค๐Ÿ‘ค๐Ÿ‘คPath 1: Start at 0, k=2 jumps5 + (-3) + (-4) = -2๐Ÿ‘ค๐Ÿ‘คPath 2: Start at 1, k=2 jumps2 + 1 = 3 โญ MAXIMUM!๐ŸŽฏ Strategy: Try each starting position, find the path with maximum energy sum
Understanding the Visualization
1
Choose starting position
Pick any magician from position 0 to n-1 as your starting point
2
Absorb and teleport
Take the magician's energy (positive or negative) and jump k positions forward
3
Repeat until end
Continue the process until you can't jump k positions anymore
4
Find maximum
The goal is to find the starting position that gives maximum total energy
Key Takeaway
๐ŸŽฏ Key Insight: Since we can only jump k positions at a time, there are at most k unique jumping patterns. We can optimize by calculating each pattern once using dynamic programming.
Asked in
Meta 25 Amazon 18 Google 15 Microsoft 12
28.4K Views
Medium Frequency
~15 min Avg. Time
892 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