|
| 1 | +/** |
| 2 | + * 3186. Maximum Total Damage With Spell Casting |
| 3 | + * https://leetcode.com/problems/maximum-total-damage-with-spell-casting/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * A magician has various spells. |
| 7 | + * |
| 8 | + * You are given an array power, where each element represents the damage of a spell. Multiple |
| 9 | + * spells can have the same damage value. |
| 10 | + * |
| 11 | + * It is a known fact that if a magician decides to cast a spell with a damage of power[i], |
| 12 | + * they cannot cast any spell with a damage of power[i] - 2, power[i] - 1, power[i] + 1, or |
| 13 | + * power[i] + 2. |
| 14 | + * |
| 15 | + * Each spell can be cast only once. |
| 16 | + * |
| 17 | + * Return the maximum possible total damage that a magician can cast. |
| 18 | + */ |
| 19 | + |
| 20 | +/** |
| 21 | + * @param {number[]} power |
| 22 | + * @return {number} |
| 23 | + */ |
| 24 | +var maximumTotalDamage = function(power) { |
| 25 | + const frequency = new Map(); |
| 26 | + for (const p of power) { |
| 27 | + frequency.set(p, (frequency.get(p) || 0) + 1); |
| 28 | + } |
| 29 | + |
| 30 | + const uniquePowers = Array.from(frequency.keys()).sort((a, b) => a - b); |
| 31 | + const n = uniquePowers.length; |
| 32 | + |
| 33 | + if (n === 0) return 0; |
| 34 | + if (n === 1) return uniquePowers[0] * frequency.get(uniquePowers[0]); |
| 35 | + |
| 36 | + const dp = new Array(n).fill(0); |
| 37 | + dp[0] = uniquePowers[0] * frequency.get(uniquePowers[0]); |
| 38 | + |
| 39 | + for (let i = 1; i < n; i++) { |
| 40 | + const currentPower = uniquePowers[i]; |
| 41 | + const currentDamage = currentPower * frequency.get(currentPower); |
| 42 | + |
| 43 | + let j = i - 1; |
| 44 | + while (j >= 0 && uniquePowers[j] >= currentPower - 2) { |
| 45 | + j--; |
| 46 | + } |
| 47 | + |
| 48 | + const withCurrent = currentDamage + (j >= 0 ? dp[j] : 0); |
| 49 | + const withoutCurrent = dp[i - 1]; |
| 50 | + |
| 51 | + dp[i] = Math.max(withCurrent, withoutCurrent); |
| 52 | + } |
| 53 | + |
| 54 | + return dp[n - 1]; |
| 55 | +}; |
0 commit comments