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的位只算了一次

相关推荐
爱coding的橙子2 小时前
每日算法刷题Day78:10.23:leetcode 一般树7道题,用时1h30min
算法·leetcode·深度优先
Swift社区3 小时前
LeetCode 403 - 青蛙过河
算法·leetcode·职场和发展
Dream it possible!4 小时前
LeetCode 面试经典 150_链表_两数相加 (57_2_C++_中等)
leetcode·链表·面试
仰泳的熊猫10 小时前
LeetCode:51. N 皇后
数据结构·c++·算法·leetcode
独自破碎E10 小时前
LeetCode 381: O(1) 时间插入、删除和获取随机元素 - 允许重复
java·算法·leetcode
Miraitowa_cheems10 小时前
LeetCode算法日记 - Day 81: 最大子数组和
java·数据结构·算法·leetcode·决策树·职场和发展·深度优先
im_AMBER12 小时前
Leetcode 35
笔记·学习·算法·leetcode
码农多耕地呗12 小时前
力扣101.对称二叉树(java)
算法·leetcode
软行14 小时前
LeetCode 每日一题 166. 分数到小数
数据结构·c++·算法·leetcode·哈希算法
阿昭L14 小时前
leetcode合并有序链表
leetcode·链表