[LeetCode] Apply Operations to Make Sum of Array Greater Than or Equal to k

3091. Apply Operations to Make Sum of Array Greater Than or Equal to k

You are given a positive integer k. Initially, you have an array nums = [1].

You can perform any of the following operations on the array any number of times (possibly zero):

  • Choose any element in the array and increase its value by 1.
  • Duplicate any element in the array and add it to the end of the array.

Return the minimum number of operations required to make the sum of elements of the final array greater than or equal to k.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int minOperations(int k) {
int res = k - 1;
for(int i = 1; i <= k and i <= res; i++) {
int op = i - 1;
int mul = max(1, (k + i - 1) / i - 1);
res = min(res, op + mul);
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2024/03/24/PS/LeetCode/apply-operations-to-make-sum-of-array-greater-than-or-equal-to-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.