leetcode算法题--使子序列的和等于目标的最少操作次数

原题链接: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  
}
相关推荐
Kuo-Teng11 分钟前
LeetCode 19: Remove Nth Node From End of List
java·数据结构·算法·leetcode·链表·职场和发展·list
Kuo-Teng15 分钟前
LeetCode 21: Merge Two Sorted Lists
java·算法·leetcode·链表·职场和发展
2301_8003997226 分钟前
stm32 printf重定向到USART
java·stm32·算法
顾安r2 小时前
11.15 脚本算法 加密网页
服务器·算法·flask·html·同态加密
前端小L2 小时前
图论专题(四):DFS的“回溯”之舞——探寻「所有可能路径」
算法·深度优先·图论
司铭鸿2 小时前
数学图论的艺术:解码最小公倍数图中的连通奥秘
运维·开发语言·算法·游戏·图论
元亓亓亓2 小时前
LeetCode热题100--39. 组合总和
算法·leetcode·职场和发展
2401_841495642 小时前
【LeetCode刷题】找到字符串中所有字母异位词
数据结构·python·算法·leetcode·数组·滑动窗口·找到字符串中所有字母异位词
橘颂TA3 小时前
【剑斩OFFER】算法的暴力美学——寻找数组的中心下标
算法·leetcode·职场和发展·结构与算法
py有趣3 小时前
LeetCode算法学习之鸡蛋掉落
学习·算法·leetcode