LeetCode 题解工作台

执行操作使数据元素之和大于等于 K

给你一个 正整数 k 。最初,你有一个数组 nums = [1] 。 你可以对数组执行以下 任意 操作 任意 次数( 可能为零 ): 选择数组中的任何一个元素,然后将它的值 增加 1 。 复制数组中的任何一个元素,然后将它附加到数组的末尾。 返回使得最终数组元素之 和 大于或等于 k 所需的 最少 …

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

中等 · 贪心·invariant

bolt

答案摘要

我们应该将复制的操作(即操作 )放后面,这样可以减少操作次数。 因此,我们在 $[0, k]$ 的范围内枚举操作 的次数 ,那么操作 的次数 $b = \left\lceil \frac{k}{a+1} \right\rceil - 1$。取最小的 即可。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个正整数 k 。最初,你有一个数组 nums = [1]

你可以对数组执行以下 任意 操作 任意 次数(可能为零):

  • 选择数组中的任何一个元素,然后将它的值 增加 1
  • 复制数组中的任何一个元素,然后将它附加到数组的末尾。

返回使得最终数组元素之大于或等于 k 所需的 最少 操作次数。

 

示例 1:

输入:k = 11

输出:5

解释:

可以对数组 nums = [1] 执行以下操作:

  • 将元素的值增加 1 三次。结果数组为 nums = [4]
  • 复制元素两次。结果数组为 nums = [4,4,4]

最终数组的和为 4 + 4 + 4 = 12 ,大于等于 k = 11
执行的总操作次数为 3 + 2 = 5

示例 2:

输入:k = 1

输出:0

解释:

原始数组的和已经大于等于 1 ,因此不需要执行操作。

 

提示:

  • 1 <= k <= 105
lightbulb

解题思路

方法一:枚举

我们应该将复制的操作(即操作 22)放后面,这样可以减少操作次数。

因此,我们在 [0,k][0, k] 的范围内枚举操作 11 的次数 aa,那么操作 22 的次数 b=ka+11b = \left\lceil \frac{k}{a+1} \right\rceil - 1。取最小的 a+ba+b 即可。

时间复杂度 O(k)O(k),其中 kk 为输入的正整数 kk。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
class Solution:
    def minOperations(self, k: int) -> int:
        ans = k
        for a in range(k):
            x = a + 1
            b = (k + x - 1) // x - 1
            ans = min(ans, a + b)
        return ans
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for an understanding of greedy strategies in optimizing sum with minimal operations.

  • question_mark

    Check the candidate’s ability to prioritize operations effectively.

  • question_mark

    Evaluate how well the candidate validates their approach using mathematical principles and invariant rules.

warning

常见陷阱

外企场景
  • error

    Misprioritizing operations, leading to excess operations before reaching k.

  • error

    Failing to account for the efficient handling of duplicate operations.

  • error

    Neglecting invariant validation that ensures all operations move toward the target sum.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if nums starts with more elements than just [1]?

  • arrow_right_alt

    What if the array is very large, requiring different optimization strategies?

  • arrow_right_alt

    How can this problem be approached with dynamic programming for different constraints?

help

常见问题

外企场景

执行操作使数据元素之和大于等于 K题解:贪心·invariant | LeetCode #3091 中等