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
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.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code