3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K

3007. Maximum Number That Sum of the Prices Is Less Than or Equal to K

python 复制代码
class Solution:
    def findMaximumNumber(self, k: int, x: int) -> int:
        def check(v):
            A=list(map(int,bin(v)[2:]))
            n=len(A)
            res=p=0
            for i,v in enumerate(A):
                if v==1:
                    l=n-i-1
                    res+=(p<<l)+((l//x)<<(l-1) if l else 0)
                if (n-i)%x==0:
                    p+=v
            return res+p

        l,r=1,10**15
        while l<r:
            mid=(l+r+1)//2
            if check(mid)<=k:
                l=mid
            else:
                r=mid-1
        return l

p记录的是前面有几位可以是1

l表示空闲位

l//x表示空闲位中可以为1,位的个数

(l-1)表示当其中一位设置为1,剩余位的个数

这里会重复枚举数字,但是每个为1的位只算了一次

相关推荐
lightqjx13 小时前
【算法】双指针
c++·算法·leetcode·双指针
sin_hielo13 小时前
leetcode 2147
数据结构·算法·leetcode
萌>__<新13 小时前
力扣打卡每日一题——缺失的第一个正数
数据结构·算法·leetcode
萌>__<新14 小时前
力扣打卡每日一题————零钱兑换
算法·leetcode·职场和发展
重生之后端学习14 小时前
238. 除自身以外数组的乘积
java·数据结构·算法·leetcode·职场和发展·哈希算法
Learner__Q14 小时前
每天五分钟:动态规划-LeetCode高频题_day2
算法·leetcode·动态规划
Dream it possible!16 小时前
LeetCode 面试经典 150_字典树_添加与搜索单词 - 数据结构设计(96_211_C++_中等)
c++·leetcode·面试·字典树
月明长歌17 小时前
【码道初阶】【LeetCode 572】另一棵树的子树:当“递归”遇上“递归”
算法·leetcode·职场和发展
月明长歌17 小时前
【码道初阶】【LeetCode 150】逆波兰表达式求值:为什么栈是它的最佳拍档?
java·数据结构·算法·leetcode·后缀表达式