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

相关推荐
驭渊的小故事9 小时前
LeetCode 算法题解:滑动窗口与数组合并的实战应用
算法·leetcode·职场和发展
文丑颜不良啊9 小时前
LeetCode1501~1520题目解析
java·leetcode
Navigator_Z11 小时前
LeetCode //C - 1311. Get Watched Videos by Your Friends
c语言·算法·leetcode
Pniubi12 小时前
力扣42接雨水(动态规划法)
算法·leetcode·职场和发展
Pniubi12 小时前
力扣46全排列(回溯(递归))
算法·leetcode·职场和发展
文丑颜不良啊13 小时前
LeetCode1461~1480题目解析
java·leetcode
Pniubi1 天前
力扣283移动零(双指针法)
算法·leetcode·职场和发展
旖旎夜光1 天前
LeetCode 315: 算右侧小于当前元素的个数(归并排序) —— 题解
c++·学习·算法·leetcode·排序算法
文丑颜不良啊1 天前
LeetCode1401~1420题目解析
java·leetcode
Nuanyt1 天前
LeetCode Hot 100 链表专题2 3 题 (Java)
java·笔记·算法·leetcode·链表