LeetCode每日一题——2558. Take Gifts From the Richest Pile

文章目录

一、题目

2558. Take Gifts From the Richest Pile

You are given an integer array gifts denoting the number of gifts in various piles. Every second, you do the following:

Choose the pile with the maximum number of gifts.

If there is more than one pile with the maximum number of gifts, choose any.

Leave behind the floor of the square root of the number of gifts in the pile. Take the rest of the gifts.

Return the number of gifts remaining after k seconds.

Example 1:

Input: gifts = 25,64,9,4,100, k = 4

Output: 29

Explanation:

The gifts are taken in the following way:

  • In the first second, the last pile is chosen and 10 gifts are left behind.
  • Then the second pile is chosen and 8 gifts are left behind.
  • After that the first pile is chosen and 5 gifts are left behind.
  • Finally, the last pile is chosen again and 3 gifts are left behind.
    The final remaining gifts are 5,8,9,4,3, so the total number of gifts remaining is 29.
    Example 2:

Input: gifts = 1,1,1,1, k = 4

Output: 4

Explanation:

In this case, regardless which pile you choose, you have to leave behind 1 gift in each pile.

That is, you can't take any pile with you.

So, the total gifts remaining are 4.

Constraints:

1 <= gifts.length <= 103

1 <= giftsi <= 109

1 <= k <= 103

二、题解

由于每次都需要重复"取最大值"的操作,因此使用最大堆进行存储,优化时间复杂度

cpp 复制代码
class Solution {
public:
    long long pickGifts(vector<int>& gifts, int k) {
        priority_queue<int> q(gifts.begin(),gifts.end());
        while(k--){
            int tmp = q.top();
            q.pop();
            q.push(int(sqrt(tmp)));
        }
        long long res = 0;
        while(!q.empty()){
            res += q.top();
            q.pop();
        }
        return res;
    }
};
相关推荐
明月_清风1 小时前
从二叉树到 B+ 树:一文搞懂工程中「树」的演化之道
数据结构·算法·go
渡我白衣1 小时前
并查集:基础认识与模拟实现
android·java·javascript·数据结构·c++·算法·并查集
如意猴1 小时前
【C++】001--C++入门(1)
开发语言·c++
hetao17338371 小时前
2026-09-01~09-04 hetao1733837 的刷题记录
c++·算法
Evand J1 小时前
【MATLAB例程,图像滤波5】 反谐波均值滑动窗口滤波(CHMF)图像降噪与质量评价,附代码下载链接
图像处理·算法·计算机视觉·matlab·均值算法·滑动窗口滤波·均值滑动
血小板要健康2 小时前
链表 阶段算法总结
java·数据结构·笔记·算法·leetcode·链表
a187927218312 小时前
【算法】回溯算法(三):三记重锤与 N 皇后——记忆化、状态设计与三层漏斗
算法·leetcode·go·剪枝·回溯·n皇后·算法讲解
HugoStudio_SWAN4 小时前
洛谷 P1420 / P1179 / B4262 最长连号、数字统计与词频统计——统计的三种面孔
c++·学习·程序人生·算法
青 春 记 忆5 小时前
LeetCode 350. 两个数组的交集 II|Python 解法详解
python·算法·leetcode
raindayinrain5 小时前
c++并发
c++