Maximum Number That Sum of the Prices Is Less Than or Equal to K Problem
Description
LeetCode Problem 3007.
You are given an integer k and an integer x. The price of a number num is calculated by the count of set bits at positions x, 2x, 3x, etc., in its binary representation, starting from the least significant bit. The following table contains examples of how price is calculated.
| x | num | Binary Representation | Price |
|---|---|---|---|
| 1 | 13 | 000001101 | 3 |
| 2 | 13 | 000001101 | 1 |
| 2 | 233 | 011101001 | 3 |
| 3 | 13 | 000001101 | 1 |
| 3 | 362 | 101101010 | 2 |
The accumulated price of num is the total price of numbers from 1 to num. num is considered cheap if its accumulated price is less than or equal to k.
Return the greatest cheap number.
Example 1:
Input: k = 9, x = 1
Output: 6
Explanation:
As shown in the table below, 6 is the greatest cheap number.
x num Binary Representation Price Accumulated Price
1 1 001 1 1
1 2 010 1 2
1 3 011 2 4
1 4 100 1 5
1 5 101 2 7
1 6 110 2 9
1 7 111 3 12
Example 2:
Input: k = 7, x = 2
Output: 9
Explanation:
As shown in the table below, 9 is the greatest cheap number.
x num Binary Representation Price Accumulated Price
2 1 0001 0 0
2 2 0010 1 1
2 3 0011 1 2
2 4 0100 0 2
2 5 0101 0 2
2 6 0110 1 3
2 7 0111 1 4
2 8 1000 1 5
2 9 1001 1 6
2 10 1010 2 8
Constraints:
1 <= k <= 10^151 <= x <= 8
Solution
Approach: Binary Search + Digit DP
The accumulated price of num never decreases as num grows, so the greatest cheap number can be found by binary search.
Search num in [1, 10^17] (a value in this range already has a total far above 10^15, so the answer lies inside). For each candidate mid, compute the total price of all numbers from 1 to mid with a digit DP over its binary digits: dfs(pos, cnt, limit) walks from the highest bit down, counts the set bits at positions that are multiples of x, and sums over every number not larger than mid. If the total is at most k, move the lower end up to mid; otherwise move the upper end below it.
Complexity: O(log2 k) time, since there are O(log k) binary-search steps and each DP costs O(log k) states, and O(log k) space.
from functools import lru_cache
class Solution:
def findMaximumNumber(self, k: int, x: int) -> int:
@lru_cache(None)
def dfs(pos, limit, cnt):
if pos == 0:
return cnt
ans = 0
up = (self.num >> (pos - 1) & 1) if limit else 1
for i in range(up + 1):
ans += dfs(pos - 1, limit and i == up, cnt + (i == 1 and pos % x == 0))
return ans
l, r = 1, 10**18
while l < r:
mid = (l + r + 1) >> 1
self.num = mid
v = dfs(mid.bit_length(), True, 0)
dfs.cache_clear()
if v <= k:
l = mid
else:
r = mid - 1
return l