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 Number with Price Sum ≤ K INPUT k = 9 x = 1 Price Calculation (x=1) Count ALL set bits num binary price 1 001 1 2 010 1 3 011 2 4 100 1 5 101 2 6 110 2 Accumulated Prices: 1+1+2+1+2+2 = 9 Sum(1..6) = 9 ≤ k Sum(1..7) = 12 > k ALGORITHM STEPS 1 Binary Search Setup Search range: [1, 10^15] Find max num where sum ≤ k 2 DP for Bit Counting Count set bits at positions x, 2x, 3x... for [1,mid] 3 Digit DP Calculation Process each bit position Accumulate price sum 4 Binary Search Check If sum ≤ k: search higher Else: search lower Binary Search Progress mid=3: sum=4 ≤ 9 [OK] mid=5: sum=7 ≤ 9 [OK] mid=6: sum=9 ≤ 9 [OK] mid=7: sum=12 > 9 [X] FINAL RESULT Answer: 6 Verification: Numbers 1 to 6: Prices: 1+1+2+1+2+2 Total = 9 ≤ k=9 [OK] Numbers 1 to 7: Total = 12 > k=9 [X] Greatest Cheap Number = 6 Key Insight: Binary search on the answer combined with Digit DP efficiently computes accumulated prices. For x=1, we count all set bits. Digit DP counts bits at positions x, 2x, 3x... for numbers [1,num]. Time Complexity: O(log^2(max_num) * bits) where bits is the number of binary digits. TutorialsPoint - Maximum Number That Sum of the Prices Is Less Than or Equal to K | DP Approach
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