原题链接:https://leetcode.cn/problems/minimum-operations-to-form-subsequence-with-target-sum/description/
视频讲解:https://www.bilibili.com/video/BV1Em4y1T7Bq?t=1456.1
这题是真的难。。
go
func minOperations(nums []int, target int) int {
s:= 0
cnt := [31]int{}
for _, num := range nums {
s += num
cnt[bits.TrailingZeros(uint(num))]++
}
if s < target {
return -1
}
if s == target {
return 0
}
s = 0
ans := 0
i := 0
for 1 << i <= target {
s += cnt[i] << i // cnt[i] * (1 << i)
mask := 1<<(i+1) - 1
if s >= target&mask {
// if s >= target&mask > (2 ^ i)
// 可以由小于target&mask的数合成
i++
continue
}
ans++
// 比如从32(2^5)分到8(2^3), 32 -> 16 -> 8, 需要5-3=2次
for i++; cnt[i] == 0; i++ {
ans++
}
}
return ans
}