---
# System prepended metadata

title: LeetCode 3091. Apply Operations to Make Sum of Array Greater Than or Equal to k
tags: [Leetcode]

---

# LeetCode 3091. Apply Operations to Make Sum of Array Greater Than or Equal to k
[LeetCode 3091. Apply Operations to Make Sum of Array Greater Than or Equal to k](https://leetcode.com/problems/apply-operations-to-make-sum-of-array-greater-than-or-equal-to-k) (<font color=#FFB800>Medium</font> 44.5%)
<!-- 
(<font color=#00AF9B>Easy</font> 53.8%) 
(<font color=#FFB800>Medium</font> 39.6%)
(<font color=#FF375F>Hard</font>)
 -->
    
- 限制 :

    <ul>
    <li><code>1 <= k <= 10^5</code></li>
    </ul>

- Solution
    計算 k 的平方根 sqrt_num。如果 k 是完全平方數，最小操作數為 sqrt_num + sqrt_num - 2。如果 k 接近完全平方數，則為 sqrt_num + sqrt_num - 1。其他情況下，操作數量為 sqrt_num + sqrt_num。
    - 時間複雜度: $O(1)$
    - 空間複雜度: $O(1)$

- 程式碼
    ```c++=
    class Solution {
    public:
        int minOperations(int k) {
            int sqrt_num = sqrt(k);
            if (sqrt_num * sqrt_num == k)
                return sqrt_num + sqrt_num - 2;
            else if ((sqrt_num + 1) * sqrt_num >= k) {
                return sqrt_num + sqrt_num - 1;
            } else
                return sqrt_num + sqrt_num;
        }
    };
    ```
