LeetCode每日一题(2195. Append K Integers With Minimal Sum)

给定数组nums和整数k,添加k个不重复的正整数到nums,使得最终和最小。返回所添加的k个数的和。题目要求对nums排序,计算相邻元素间的间隙之和,若k大于间隙数,则用nums的最大值之后的数填充剩余位置,反之则可能有部分间隙无法完全填充。
摘要由CSDN通过智能技术生成

You are given an integer array nums and an integer k. Append k unique positive integers that do not appear in nums to nums such that the resulting total sum is minimum.

Return the sum of the k integers appended to nums.

Example 1:

Input: nums = [1,4,25,10,25], k = 2
Output: 5

Explanation: The two unique positive integers that do not appear in nums which we append are 2 and 3.
The resulting sum of nums is 1 + 4 + 25 + 10 + 25 + 2 + 3 = 70, which is the minimum.
The sum of the two integers appended is 2 + 3 = 5, so we return 5.

Example 2:

Input: nums = [5,6], k = 6
Output: 25

Explanation: The six unique positive integers that do not appear in nums which we append are 1, 2, 3, 4, 7, and 8.
The resulting sum of nums is 5 + 6 + 1 + 2 + 3 + 4 + 7 + 8 = 36, which is the minimum.
The sum of the six integers appended is 1 + 2 + 3 + 4 + 7 + 8 = 25, so we return 25.

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109
  • 1 <= k <= 108

  1. 将 nums 排序
  2. nums 中相邻两个数之间的间隙,将这些间隙加起来, 例如 1, 4 之间的间隙就是 2, 3, 加和就是 2 + 3 = 5
  3. 需要注意的是数量 k, 如果数量 k 大于 nums 中所有间隙数字的数量那就需要用 max(nums)之后的数字来填补这个数量差, 如果 k 小于 nums 中所有间隙数字在的数量那就有可能某个间隙数字不能全部加到答案中

impl Solution {
   
    pub fn minimal_k_sum(mut nums: Vec<i32>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值