Fork me on github

【每日一题】740. 删除并获得点数

https://leetcode-cn.com/problems/delete-and-earn/
开始的使用使用贪心算法,优先删除那些数量最多的元素,如果两个元素的数量相同,那就先删除大的
结果没有过

import java.util.*;

class Solution {
    int res = 0;
    public int deleteAndEarn(int[] nums) {
        Map<Integer, Integer> map = new HashMap<>();
        List<Integer> list = new ArrayList<>();

        for(int n : nums){
            if(map.containsKey(n)){
                map.put(n, map.get(n) + 1);
            }
            else{
                list.add(n);
                map.put(n, 1);
            }
        }

        list.sort((o1, o2) -> {
            int count1 = map.get(o1);
            int count2 = map.get(o2);
            if(count1 == count2){
                return o2 - o1;
            }
            return count2 - count1;
        });

        System.out.println(list);

        for(int n : list){
            int count = map.get(n);
            while(count > 0){
                count --;
                System.out.println("n = " + n);
                res += n;
                if(map.containsKey(n + 1)){
                    map.put(n + 1, -1);
                }
                if(map.containsKey(n - 1)){
                    map.put(n - 1, -1);
                }
            }
        }

        return res;
    }
}
  1. 当前位置元素不删除,和 i - 1 位置最优解一样
  2. 当前位置元素删除,最优解为 i - 2 位置最优解 + 当前位置元素 * count

看别人的题解使用动态规划

class Solution {
    public int deleteAndEarn(int[] nums) {
        int[] count = new int[10001];
        for(int n : nums){
            count[n] ++;
        }
        int[] dp = new int[10001];
        dp[1] = count[1] * 1;
        dp[2] = Math.max(dp[1], count[2] * 2);
        for(int i = 2; i < 10001; i++){
            dp[i] = Math.max(dp[i - 1], dp[i - 2] + i * count[i]);
        }
        return dp[10000];
    }
}
posted @ 2021-05-06 19:55  zjy4fun  阅读(58)  评论(0编辑  收藏  举报