Skip to content

Leetcode 2813. Maximum Elegance of a K-Length Subsequence #283

Open
@Woodyiiiiiii

Description

@Woodyiiiiiii

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和排序了。

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;
    }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions