0
点赞
收藏
分享

微信扫一扫

从零手写实现 nginx-23-nginx 对于 cookie 的操作

LeetCode-day11-2813. 子序列最大优雅度

题目描述

给你一个长度为 n 的二维整数数组 items 和一个整数 k 。

items[i] = [profiti, categoryi],其中 profiti 和 categoryi 分别表示第 i 个项目的利润和类别。

现定义 items 的 子序列优雅度 可以用 total_profit + distinct_categories2 计算,其中 total_profit 是子序列中所有项目的利润总和,distinct_categories 是所选子序列所含的所有类别中不同类别的数量。

你的任务是从 items 所有长度为 k 的子序列中,找出 最大优雅度

用整数形式表示并返回 items 中所有长度恰好为 k 的子序列的最大优雅度。

注意:数组的子序列是经由原数组删除一些元素(可能不删除)而产生的新数组,且删除不改变其余元素相对顺序。

示例

示例1:

示例2:

示例3:

思路

采用贪心策略。

代码

 public long findMaximumElegance(int[][] items, int k) {
        Arrays.sort(items,(a,b) -> b[0] - a[0]);
        long ans = 0;
        long totalProfit = 0;
        Set<Integer>  set = new HashSet<>();
        Deque<Integer> deque = new ArrayDeque<>();
        for (int i = 0; i < items.length; i++) {
            int profit = items[i][0];
            int category = items[i][1];
            if (i < k){
                totalProfit += profit;
                if (!set.add(category)){
                    deque.push(profit);
                }
            } else if (!deque.isEmpty() && set.add(category)) {
                totalProfit += profit - deque.pop();
            }
            ans = Math.max(ans,totalProfit+ (long) set.size() * set.size());
        }
        return ans;
    }
举报

相关推荐

0 条评论