We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
2813. Maximum Elegance of a K-Length Subsequence
类似题目和讲解: Leetcode 1383. Maximum Performance of a Team / 502. IPO 反悔贪心(Python/Java/C++/Go)
这道题我一开始想用DP,但因为有两个这么大的变量,就应该排除这个方法。必须想方法把一个变量给去掉,因为k更重要,想办法把n去掉。那就要想到贪心/排序/PQ/二分了。
按照排序的方法,那按照什么排序呢?看关键公式,和我们可以用堆来处理,所以先按照利润从大到小排序,取完前面k个后,往后面就依次考虑能否取值使得结果变大。
模版题。我应该一开始就往排序/堆/贪心考虑的,因为subsequences最常见的也就是DP和排序了。
class Solution { public long findMaximumElegance(int[][] items, int k) { Arrays.sort(items, (a, b) -> b[0] - a[0]); long ans = 0, totalProfit = 0; Set<Integer> categories = new HashSet<>(); PriorityQueue<Integer> pq = new PriorityQueue<>(); for (int i = 0; i < items.length; i++) { if (i < k) { totalProfit += items[i][0]; if (!categories.contains(items[i][1])) { categories.add(items[i][1]); } else { pq.offer(items[i][0]); } ans = Math.max(ans, totalProfit + (long) categories.size() * categories.size()); } else if (!pq.isEmpty() && !categories.contains(items[i][1])) { int min = pq.poll(); totalProfit = totalProfit - min + items[i][0]; categories.add(items[i][1]); ans = Math.max(ans, totalProfit + (long) categories.size() * categories.size()); } } return ans; } }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
2813. Maximum Elegance of a K-Length Subsequence
2813. Maximum Elegance of a K-Length Subsequence
类似题目和讲解:
Leetcode 1383. Maximum Performance of a Team / 502. IPO
反悔贪心(Python/Java/C++/Go)
这道题我一开始想用DP,但因为有两个这么大的变量,就应该排除这个方法。必须想方法把一个变量给去掉,因为k更重要,想办法把n去掉。那就要想到贪心/排序/PQ/二分了。
按照排序的方法,那按照什么排序呢?看关键公式,和我们可以用堆来处理,所以先按照利润从大到小排序,取完前面k个后,往后面就依次考虑能否取值使得结果变大。
模版题。我应该一开始就往排序/堆/贪心考虑的,因为subsequences最常见的也就是DP和排序了。
The text was updated successfully, but these errors were encountered: