Skip to content

Commit b2b04a1

Browse files
Merge pull request #317 from tiennguyen2310/patch-95
Create TakingMaximumEnergyFromTheMysticDungeon.java
2 parents 9f087e6 + dc3e8fc commit b2b04a1

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*
2+
3147. Taking Maximum Energy From the Mystic Dungeon
3+
Solved
4+
Medium
5+
Topics
6+
premium lock icon
7+
Companies
8+
Hint
9+
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.
10+
11+
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.
12+
13+
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.
14+
15+
You are given an array energy and an integer k. Return the maximum possible energy you can gain.
16+
17+
Note that when you are reach a magician, you must take energy from them, whether it is negative or positive energy.
18+
19+
20+
21+
Example 1:
22+
23+
Input: energy = [5,2,-10,-5,1], k = 3
24+
25+
Output: 3
26+
27+
Explanation: We can gain a total energy of 3 by starting from magician 1 absorbing 2 + 1 = 3.
28+
29+
Example 2:
30+
31+
Input: energy = [-2,-3,-1], k = 2
32+
33+
Output: -1
34+
35+
Explanation: We can gain a total energy of -1 by starting from magician 2.
36+
37+
38+
39+
Constraints:
40+
41+
1 <= energy.length <= 105
42+
-1000 <= energy[i] <= 1000
43+
1 <= k <= energy.length - 1
44+
*/
45+
class Solution {
46+
public int maximumEnergy(int[] energy, int k) {
47+
int res = -100000;
48+
int n = energy.length;
49+
for(int i = n - k; i < n; i++){
50+
//traverse backward
51+
int cur = 0;
52+
for(int j = i; j >= 0; j -= k){
53+
cur += energy[j];
54+
res = Math.max(res, cur);
55+
}
56+
}
57+
return res;
58+
}
59+
}

0 commit comments

Comments
 (0)