|
| 1 | +/** |
| 2 | + * 3147. Taking Maximum Energy From the Mystic Dungeon |
| 3 | + * https://leetcode.com/problems/taking-maximum-energy-from-the-mystic-dungeon/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * In a mystic dungeon, n magicians are standing in a line. Each magician has an attribute |
| 7 | + * that gives you energy. Some magicians can give you negative energy, which means taking |
| 8 | + * energy from you. |
| 9 | + * |
| 10 | + * You have been cursed in such a way that after absorbing energy from magician i, you will |
| 11 | + * be instantly transported to magician (i + k). This process will be repeated until you |
| 12 | + * reach the magician where (i + k) does not exist. |
| 13 | + * |
| 14 | + * In other words, you will choose a starting point and then teleport with k jumps until you |
| 15 | + * reach the end of the magicians' sequence, absorbing all the energy during the journey. |
| 16 | + * |
| 17 | + * You are given an array energy and an integer k. Return the maximum possible energy you can gain. |
| 18 | + * |
| 19 | + * Note that when you are reach a magician, you must take energy from them, whether it is negative |
| 20 | + * or positive energy. |
| 21 | + */ |
| 22 | + |
| 23 | +/** |
| 24 | + *@param {number[]} energy |
| 25 | + *@param {number} k |
| 26 | + *@return {number} |
| 27 | + */ |
| 28 | +varmaximumEnergy=function(energy,k){ |
| 29 | +constn=energy.length; |
| 30 | +constdp=newArray(n).fill(0); |
| 31 | +letresult=-Infinity; |
| 32 | + |
| 33 | +for(leti=n-1;i>=0;i--){ |
| 34 | +dp[i]=energy[i]+(i+k<n ?dp[i+k] :0); |
| 35 | +result=Math.max(result,dp[i]); |
| 36 | +} |
| 37 | + |
| 38 | +returnresult; |
| 39 | +}; |