3007. 价值和小于等于 K 的最大数字
3007. 价值和小于等于 K 的最大数字
题目链接:3007. 价值和小于等于 K 的最大数字
代码如下:
//参考链接:https://leetcode.cn/problems/maximum-number-that-sum-of-the-prices-is-less-than-or-equal-to-k/solutions/2603673/er-fen-da-an-shu-wei-dpwei-yun-suan-pyth-tkir
class Solution
{
public:
long long findMaximumNumber(long long k, int x)
{
auto check=[&](long long num)
{
long long res=0;
int i=x-1;
for(long long n=num>>i;n;n>>=x,i+=x)
{
res+=(n/2)<<i;
if(n%2)
{
long long mask=(1LL<<i)-1;
res+=(num&mask)+1;
}
}
return res<=k;
};
//二分
long long left=0,right=(k+1)<<x;
while(left+1<right)
{
long long mid=left+(right-left)/2;
(check(mid)?left:right)=mid;
}
return left;
}
};