[LeetCode] 2530. Maximal Score After Applying K Operations
You are given a 0-indexed integer array nums and an integer k. You have a starting score of 0.
In one operation:
choose an index i such that 0 <= i < nums.length,
increase your score by nums[i], and
replace nums[i] with ceil(nums[i] / 3).
Return the maximum possible score you can attain after applying exactly k operations.
The ceiling function ceil(val) is the least integer greater than or equal to val.
Example 1:
Input: nums = [10,10,10,10,10], k = 5
Output: 50
Explanation: Apply the operation to each array element exactly once. The final score is 10 + 10 + 10 + 10 + 10 = 50.
Example 2:
Input: nums = [1,10,3,3,3], k = 3
Output: 17
Explanation: You can do the following operations:
Operation 1: Select i = 1, so nums becomes [1,4,3,3,3]. Your score increases by 10.
Operation 2: Select i = 1, so nums becomes [1,2,3,3,3]. Your score increases by 4.
Operation 3: Select i = 2, so nums becomes [1,1,1,3,3]. Your score increases by 3.
The final score is 10 + 4 + 3 = 17.
Constraints:
1 <= nums.length, k <= 105
1 <= nums[i] <= 109
执行 K 次操作后的最大分数。
给你一个下标从 0 开始的整数数组 nums 和一个整数 k 。你的 起始分数 为 0 。在一步 操作 中:
选出一个满足 0 <= i < nums.length 的下标 i ,
将你的 分数 增加 nums[i] ,并且
将 nums[i] 替换为 ceil(nums[i] / 3) 。
返回在 恰好 执行 k 次操作后,你可能获得的最大分数。向上取整函数 ceil(val) 的结果是大于或等于 val 的最小整数。
思路
思路是贪心,具体做法会用到一个最大堆。初始化的时候将 input 数组里的所有元素都放入最大堆,然后每次弹出堆顶元素 top,将这个元素的值累加到结果 res,然后再把 top 除以 3 再放回最大堆,如此一套流程执行 k 次之后停止。
复杂度
时间O(nlogn) - 也可以是O(nlogk),取决于你怎么创建这个最大堆
空间O(n) - 也可以是O(k),取决于你怎么创建这个最大堆
代码
Java实现
class Solution { public long maxKelements(int[] nums, int k) { PriorityQueue<Double> queue = new PriorityQueue<>((a, b) -> Double.compare(b, a)); for (int num : nums) { queue.offer((double) num); } long res = 0L; while (k != 0) { double top = queue.poll(); res += top; queue.offer(Math.ceil(top / 3)); k--; } return res; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
2020-10-18 [LeetCode] 743. Network Delay Time
2020-10-18 [LeetCode] 1209. Remove All Adjacent Duplicates in String II
2020-10-18 [LeetCode] 1047. Remove All Adjacent Duplicates In String
2019-10-18 [LeetCode] 50. Pow(x, n)
2019-10-18 [LeetCode] 367. Valid Perfect Square
2019-10-18 [LeetCode] 69. Sqrt(x)