#3007
Maximum Number That Sum of the Prices Is Less Than or Equal to K
MediumMathBinary SearchDynamic ProgrammingBit ManipulationBinary SearchDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n log n)Space O(1)
Using binary search allows us to efficiently find the greatest cheap number without checking every number up to k. We can leverage the properties of the accumulated price and the price calculation to narrow down our search space.
⚙️
Algorithm
5 steps- 1Step 1: Define a function to calculate the accumulated price for a given number num.
- 2Step 2: Use binary search to find the maximum number where the accumulated price is less than or equal to k.
- 3Step 3: In each iteration of the binary search, calculate the accumulated price for the mid-point.
- 4Step 4: If the accumulated price is less than or equal to k, move the left pointer up; otherwise, move the right pointer down.
- 5Step 5: Return the left pointer as the result, which represents the greatest cheap number.
solution.py26 lines
1# Full working Python code
2
3def count_set_bits(num, x):
4 count = 0
5 pos = x
6 while pos <= num:
7 if num & pos:
8 count += 1
9 pos <<= 1
10 return count
11
12def accumulated_price(num, x):
13 total = 0
14 for i in range(1, num + 1):
15 total += count_set_bits(i, x)
16 return total
17
18def max_cheap_number(k, x):
19 left, right = 1, k
20 while left < right:
21 mid = (left + right + 1) // 2
22 if accumulated_price(mid, x) <= k:
23 left = mid
24 else:
25 right = mid - 1
26 return leftℹ
Complexity note: The time complexity is O(n log n) due to the binary search over n and the linear accumulation of prices, which is much more efficient than the brute force approach.
- 1Understanding how to calculate the price based on set bits is crucial for both approaches.
- 2Binary search significantly reduces the number of checks needed to find the maximum cheap number.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.