You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete.
Return the number of complete rows of the staircase you will build.
Example 1:
#
# #
#
Input: n = 4
Output: 2Example 2:
#
# #
# # #
# # #
Input: n = 9
Output: 3Constraints:1 <= n <= ((2^31) - 1)
We are building a staircase where row 1 needs 1 coin, row 2 needs 2 coins, and so on. The question is: how many complete rows can we build with n coins?
The simplest approach is to simulate the process. Keep adding rows one by one, subtracting the required coins from n until we cannot complete another row.
row = 0.n > row):row.row coins from n.row as the number of complete rows.Building rows one by one is slow for large n. Instead, we can use the formula for the sum of first k integers: k * (k + 1) / 2. If this sum is at most n, we can build k complete rows.
This creates a monotonic condition perfect for binary search. We search for the largest k such that k * (k + 1) / 2 <= n.
l = 1 and r = n.l <= r:mid and calculate coins needed for mid rows.n, search the left half.k.We can optimize the binary search by tightening the upper bound. Since k * (k + 1) / 2 <= n, we know k is roughly sqrt(2n). A safe upper bound is n / 2 + 1 for n > 3, which reduces the search space.
We also simplify the binary search by finding the first k where the condition fails, then returning k - 1.
n <= 3, return 1 for n = 1 and n - 1 otherwise.l = 1 and r = n / 2 + 1.k where coins exceed n.l - 1.We can build the answer bit by bit, from the most significant bit down. For each bit position, we tentatively set it and check if the resulting number of rows is valid. If valid, we keep the bit; otherwise, we clear it.
Since n fits in 32 bits and k is roughly sqrt(n), we only need about 16 bits to represent the answer.
mask at the highest relevant bit (bit 15).rows.rows rows.n, clear the bit.mask right.rows.We can solve this directly with algebra. We need the largest k where k * (k + 1) / 2 <= n. Rearranging: k^2 + k - 2n <= 0. Using the quadratic formula, k = (-1 + sqrt(1 + 8n)) / 2.
Simplifying gives us k = sqrt(2n + 0.25) - 0.5. We take the floor of this value to get the answer.
sqrt(2 * n + 0.25) - 0.5.mid * (mid + 1)When using binary search, computing mid * (mid + 1) can overflow for large values of mid if using 32-bit integers. Always cast to a larger type before multiplication.
// Wrong: overflow when mid is large
int coins = mid * (mid + 1) / 2;
// Correct: cast to long first
long coins = (long) mid * (mid + 1) / 2;The formula k * (k + 1) / 2 gives the total coins needed for k complete rows. A common mistake is returning the wrong value when the sum exactly equals n or when determining whether to include the current row.
# Wrong: returning l instead of l - 1 after binary search
while l < r:
mid = (l + r) // 2
if mid * (mid + 1) // 2 <= n:
l = mid + 1
else:
r = mid
return l # Should be l - 1