3186. Maximum Total Damage With Spell Casting

xiaoyongyong發表於2024-06-17
3186. Maximum Total Damage With Spell Casting
A magician has various spells.

You are given an array power, where each element represents the damage of a spell. Multiple spells can have the same damage value.

It is a known fact that if a magician decides to cast a spell with a damage of power[i], they cannot cast any spell with a damage of power[i] - 2, power[i] - 1, power[i] + 1, or power[i] + 2.

Each spell can be cast only once.

Return the maximum possible total damage that a magician can cast.

Example 1:

Input: power = [1,1,3,4]

Output: 6

Explanation:

The maximum possible damage of 6 is produced by casting spells 0, 1, 3 with damage 1, 1, 4.

Example 2:

Input: power = [7,1,6,6]

Output: 13

Explanation:

The maximum possible damage of 13 is produced by casting spells 1, 2, 3 with damage 1, 6, 6.

Constraints:

  • 1 <= power.length <= 105
  • 1 <= power[i] <= 109
class Solution {
    public long maximumTotalDamage(int[] power) {
        // 統計各元素個數並排序
        TreeMap<Integer, Long> map = new TreeMap<>();
        for(int p : power) {
            map.put(p, map.getOrDefault(p, 0l) + p);
        }
        // 放入list
        ArrayList<Node> list = new ArrayList<>();
        map.forEach((key, value) -> {
            list.add(new Node(key, value));
        });
        // 從第一個元素開始,計算
        return getMax(list, 0, new Long[list.size()]);
    }
    private long getMax(ArrayList<Node> list, int index, Long[] memo) {
        // 如果超出邊界直接返回0
        if(index >= list.size()) return 0;
        if(memo[index] != null) return memo[index];

        int nextIdx = index;
        // 找到下一個可以取的元素(比當前元素超出不少於2)
        while(nextIdx < list.size() && list.get(index).key >= list.get(nextIdx).key - 2) {
            nextIdx++;
        }
        // 包含當前元素的情況
        long include = list.get(index).value + getMax(list, nextIdx, memo);
        // 不包含當前元素的情況
        long exclude = getMax(list, index + 1, memo);
        memo[index] = Math.max(include, exclude);
        return memo[index];
    }
    record Node(int key, long value){}
}

相關文章