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  
}
相关推荐
To_OC6 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
旖-旎7 小时前
LeetCode 518:零钱兑换||(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
To_OC7 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
delishcomcn8 小时前
AI视觉识别+分切算法:电化铝缺陷检测与裁切一体化解锁
人工智能·算法
触底反弹8 小时前
深入理解大模型采样:Temperature、Top-K、Top-P 的原理与实战
人工智能·算法·面试
雪碧聊技术9 小时前
力扣 LCR 091. 粉刷房子 —— 动态规划入门详解
算法·动态规划
CV-Climber12 小时前
检索技术的实际应用
人工智能·算法
hhzz12 小时前
Tiger AI Platform平台中增加人脸识别功能
图像处理·人工智能·算法·计算机视觉·大模型
从零开始的代码生活_13 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法