leetcode 740. Delete and Earn | 740. 删除并获得点数(暴力递归->傻缓存->DP)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 740. Delete and Earn | 740. 删除并获得点数(暴力递归->傻缓存->DP)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
https://leetcode.com/problems/delete-and-earn/
題解
建立 help 數組,相當于一個(正向)索引表。
先排序,因為刪除的順序不影響最優結果(實際上是影響結果的,只不過最優解一定是從小到大刪除的,因為如果先刪除中間的元素的話,它的兩邊可能被誤傷,而如果從邊緣開始刪除的話,只能誤傷到一側。)
class Solution {public int deleteAndEarn(int[] nums) {Map<Integer, Integer> map = new HashMap<>();for (int n : nums) {int count = map.getOrDefault(n, 0);map.put(n, count + 1);}int[][] help = new int[map.keySet().size()][2];int p = 0;for (int k : map.keySet()) {help[p][0] = k;help[p++][1] = map.get(k);}// 刪除順序不影響結果(至少從小到大刪除結果不會更差),所以先排序Arrays.sort(help, Comparator.comparingInt(o -> o[0]));// Approach 2: Recursion with Memoization // return process(help, 0, dp);// Approach 3: Dynamic Programmingint[] dp = new int[help.length + 2];Arrays.fill(dp, -1);dp[help.length] = 0;dp[help.length + 1] = 0;for (int i = help.length - 1; i >= 0; i--) {int step = (i + 1 < help.length && help[i][0] + 1 == help[i + 1][0]) ? 2 : 1;dp[i] = Math.max(dp[i + 1], dp[i + step] + help[i][0] * help[i][1]);}return dp[0];}// 在當前i位置,刪或不刪,能夠獲得的最大收益 // public int process(int[][] help, int i, int[] dp) { // if (i >= help.length) return 0; // if (dp[i] >= 0) return dp[i]; // // int step = (i + 1 < help.length && help[i][0] + 1 == help[i + 1][0]) ? 2 : 1; // int p1 = process(help, i + 1, dp); // 不刪i位置 // int p2 = process(help, i + step, dp) + help[i][0] * help[i][1]; // 刪i位置 // // dp[i] = Math.max(p1, p2); // return dp[i]; // } }總結
以上是生活随笔為你收集整理的leetcode 740. Delete and Earn | 740. 删除并获得点数(暴力递归->傻缓存->DP)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 668. Kth Sm
- 下一篇: leetcode 720. Longes