Skip to content

Commit c03f932

Browse files
authored
Create 2835-minimum-operations-to-form-subsequence-with-target-sum.js
1 parent e537196 commit c03f932

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number}
5+
*/
6+
var minOperations = function(nums, target) {
7+
const n = nums.length, arr = Array(31).fill(0);
8+
let sum = 0;
9+
10+
for(const x of nums) ++arr[Math.log2(x)], sum += x;
11+
if(sum < target) return -1;
12+
13+
let i=0, res = 0;
14+
while(i < 31) {
15+
if(1<<i & target) {
16+
if(arr[i]) --arr[i];
17+
else {
18+
while(i < 30 && !arr[i]) ++i, ++res;
19+
--arr[i];
20+
continue;
21+
}
22+
}
23+
arr[++i] += Math.floor(arr[i-1] / 2);
24+
}
25+
26+
return res;
27+
};

0 commit comments

Comments
 (0)