Maximum Number That Sum of the Prices Is Less Than or Equal to K - Problem

You are given an integer k and an integer x.

The price of a number num is calculated by counting the number of set bits at positions x, 2x, 3x, etc., in its binary representation (starting from the least significant bit at position 1).

For example:

  • If x = 1 and num = 13 (binary: 1101), we check positions 1, 2, 3, 4, ... The set bits at positions 1, 3, 4 give us a price of 3.
  • If x = 2 and num = 13 (binary: 1101), we check positions 2, 4, 6, ... The set bits at positions 2, 4 give us a price of 2.

The accumulated price of num is the total price of all numbers from 1 to num.

A number num is considered cheap if its accumulated price is less than or equal to k.

Return the greatest cheap number.

Input & Output

Example 1 — Basic Case
$ Input: k = 9, x = 1
Output: 6
💡 Note: For x=1, we count all set bits. Numbers 1-6 have accumulated price: 1+1+2+1+2+2=9 ≤ k. Number 7 would make it 9+3=12 > k.
Example 2 — Different x
$ Input: k = 7, x = 2
Output: 9
💡 Note: For x=2, we count bits at positions 2,4,6,... Numbers 1-9 have lower accumulated price since fewer positions are counted.
Example 3 — Small Budget
$ Input: k = 1, x = 1
Output: 1
💡 Note: Only number 1 (binary: 1) has price 1, accumulated price = 1 ≤ k. Number 2 would exceed budget.

Constraints

  • 1 ≤ k ≤ 1015
  • 1 ≤ x ≤ 8

Visualization

Tap to expand
Maximum Cheap Number: k=9, x=1NumberBinaryPriceAccumulatedStatus11112101231124...............611029MAX7111312When x=1: count set bits at positions 1,2,3,4,5,6,7,8...Answer: 6 (largest number with accumulated price ≤ k=9)
Understanding the Visualization
1
Input
Budget k=9, check positions x=1 (every bit)
2
Process
Calculate accumulated price for numbers 1,2,3,4,5,6...
3
Output
Maximum number 6 where accumulated price ≤ k
Key Takeaway
🎯 Key Insight: Binary search the answer space and use digit DP to efficiently calculate accumulated prices
Asked in
Google 15 Meta 8
8.5K Views
Medium Frequency
~35 min Avg. Time
245 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen