Input: k =11Output: 5Explanation:
We can do the following operations on the array `nums = [1]`:* Increase the element by `1` three times. The resulting array is`nums = [4]`.* Duplicate the element two times. The resulting array is`nums = [4,4,4]`.The sum of the final array is`4 + 4 + 4 = 12` which is greater than or equal
to `k = 11`.The total number of operations performed is`3 + 2 = 5`.
The fastest way to reach or exceed k is to repeatedly double the sum (by duplicating the largest element) until we’re close to k, then increment as needed. Duplicating increases the sum exponentially, while incrementing is linear. We minimize operations by duplicating as much as possible, then incrementing the largest element to reach or exceed k.
classSolution {
public:int minOperations(int k) {
if (k ==1) return0;
int ans =0, curr =1;
while (curr < k) {
if (curr *2<= k) {
curr *=2;
ans++;
} else {
ans += (k - curr);
curr = k;
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
publicintminOperations(int k) {
if (k == 1) return 0;
int ans = 0, curr = 1;
while (curr < k) {
if (curr * 2 <= k) {
curr *= 2;
ans++;
} else {
ans += (k - curr);
curr = k;
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
defminOperations(self, k: int) -> int:
if k ==1:
return0 ans: int =0 curr: int =1while curr < k:
if curr *2<= k:
curr *=2 ans +=1else:
ans += (k - curr)
curr = k
return ans