You are given a 0-indexed array nums consisting of non-negative powers of 2, and an integer target.
In one operation, you must apply the following changes to the array:
Choose any element of the array nums[i] such that nums[i] > 1.
Remove nums[i] from the array.
Add two occurrences of nums[i] / 2 to the end of nums.
Return the _minimum number of operations you need to perform so that _numscontains asubsequence whose elements sum totarget. If it is impossible to obtain such a subsequence, return -1.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Input: nums =[1,2,8], target =7Output: 1Explanation: In the first operation, we choose element nums[2]. The array becomes equal to nums =[1,2,4,4].At this stage, nums contains the subsequence [1,2,4] which sums up to 7.It can be shown that there is no shorter sequence of operations that results in a subsequnce that sums up to 7.
Input: nums =[1,32,1,2], target =12Output: 2Explanation: In the first operation, we choose element nums[1]. The array becomes equal to nums =[1,1,2,16,16].In the second operation, we choose element nums[3]. The array becomes equal to nums =[1,1,2,16,8,8]At this stage, nums contains the subsequence [1,1,2,8] which sums up to 12.It can be shown that there is no shorter sequence of operations that results in a subsequence that sums up to 12.
We want to form target using powers of two. If we lack a needed power, we can split a larger power into two smaller ones. The minimum number of splits is the number of times we need to break down larger powers to get enough of each bit in target.
#include<vector>#include<algorithm>usingnamespace std;
classSolution {
public:int minOperations(vector<int>& nums, int target) {
vector<int> cnt(31, 0);
for (int v : nums) cnt[__builtin_ctz(v)]++;
int ans =0;
for (int i =0; i <31; ++i) {
if ((target >> i) &1) {
if (cnt[i]) cnt[i]--;
else {
int j = i +1;
while (j <31&&!cnt[j]) ++j;
if (j ==31) return-1;
while (j > i) {
cnt[j]--;
cnt[j-1] +=2;
ans++;
j--;
}
cnt[i]--;
}
}
if (i <30) cnt[i+1] += cnt[i]/2;
}
return ans;
}
};
classSolution {
funminOperations(nums: IntArray, target: Int): Int {
val cnt = IntArray(31)
for (v in nums) cnt[v.countTrailingZeroBits()]++var ans = 0for (i in0 until 31) {
if ((target shr i) and 1==1) {
if (cnt[i] > 0) cnt[i]--else {
var j = i + 1while (j < 31&& cnt[j] ==0) j++if (j ==31) return -1while (j > i) {
cnt[j]-- cnt[j-1] +=2 ans++ j-- }
cnt[i]-- }
}
if (i < 30) cnt[i+1] += cnt[i]/2 }
return ans
}
}