Maximum Number That Sum of the Prices Is Less Than or Equal to K - Problem
Imagine you're a data analyst working with binary representations of numbers, and each number has a "price" based on specific bit positions!
Given two integers k and x, you need to find the greatest number whose accumulated price doesn't exceed k.
How is the price calculated?
- For any number
num, its price equals the count of set bits (1s) at positionsx,2x,3x, etc. in its binary representation - Bit positions are counted from the right, starting at position 1 (least significant bit)
Example: If x = 2 and num = 13 (binary: 1101):
We check positions 2, 4, 6, 8... → bits at positions 2 and 4 are both 1 → price = 2
The accumulated price of a number num is the sum of prices of all numbers from 1 to num. Find the largest number whose accumulated price ≤ k.
Input & Output
example_1.py — Basic Example
$
Input:
k = 9, x = 1
›
Output:
6
💡 Note:
With x=1, we count all set bits. Numbers 1-6 have accumulated price: 1(1)+2(1)+3(2)+4(1)+5(2)+6(2)=9, which equals k. Number 7 would add 3 more (binary 111), exceeding k.
example_2.py — Every Second Position
$
Input:
k = 7, x = 2
›
Output:
9
💡 Note:
With x=2, we only count bits at positions 2,4,6,... The accumulated price up to 9 is exactly 7, but adding number 10 (binary 1010, contributes 1) would make it 8, exceeding k.
example_3.py — Large Gap
$
Input:
k = 1, x = 8
›
Output:
255
💡 Note:
With x=8, only position 8 matters. Numbers 1-255 have no bit at position 8 (need ≥256), so accumulated price is 0. Number 256 (binary 100000000) contributes 1, making total 1.
Visualization
Tap to expand
Understanding the Visualization
1
Set Up Sensors
Place sensors at positions x, 2x, 3x, ... in the binary representation
2
Calculate Individual Price
For each number, count how many sensors detect '1' bits
3
Accumulate Costs
Sum up prices from number 1 to current number
4
Binary Search
Use binary search to find the maximum number within budget k
Key Takeaway
🎯 Key Insight: Binary search + digit DP transforms an O(n log n) problem into O(log³ n), making it feasible for k up to 10^15!
Time & Space Complexity
Time Complexity
O(n × log n)
n iterations where n is the answer, and log n time to count bits for each number
⚡ Linearithmic
Space Complexity
O(1)
Only using constant extra space for variables
✓ Linear Space
Constraints
- 1 ≤ k ≤ 1015
- 1 ≤ x ≤ 8
- k can be very large, making brute force infeasible
- x is small, making digit DP manageable
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code