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

相关推荐
Demons_kirit6 小时前
Leetcode 2845 题解
算法·leetcode·职场和发展
Wendy_robot9 小时前
【滑动窗口+哈希表/数组记录】Leetcode 438. 找到字符串中所有字母异位词
c++·算法·leetcode
程序员-King.9 小时前
day49—双指针+贪心—验证回文串(LeetCode-680)
算法·leetcode·贪心算法·双指针
Y1nhl11 小时前
力扣hot100_链表(3)_python版本
python·算法·leetcode·链表·职场和发展
前端 贾公子11 小时前
详解 LeetCode 第 242 题 - 有效的字母组
算法·leetcode·职场和发展
Demons_kirit14 小时前
LeetCode 2799、2840题解
算法·leetcode·职场和发展
软行14 小时前
LeetCode 每日一题 2845. 统计趣味子数组的数目
数据结构·c++·算法·leetcode
雾月5515 小时前
LeetCode 1292 元素和小于等于阈值的正方形的最大边长
java·数据结构·算法·leetcode·职场和发展
OpenC++16 小时前
【C++QT】Buttons 按钮控件详解
c++·经验分享·qt·leetcode·microsoft
এ᭄画画的北北17 小时前
力扣-160.相交链表
算法·leetcode·链表