I am trying to solve Arranging Coins on LeetCode.com:
You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins. Given n, find the total number of full staircase rows that can be formed. n is a non-negative integer and fits within the range of a 32-bit signed integer. For n=5, the output is: 2.
Based on the solution given, we can reformulate the problem as:
Find the maximum
k
such thatk*(k+1)/2<=N
My invariant (inspired by this Quora answer):
I have a interval from L to R such that
a[L]
<=k*(k+1)/2<=N
anda[R]
>k*(k+1)/2<=N
. Then, after I check element M in between, I set either L or R to M, preserving the invariant.
But I am unsure if my invariant is correct:
- I am unsure if this will give me the
maximum
value of k; - Should I continue the iteration
while(l<r)
orwhile(l<=r)
?l
andr
are the usual two pointers used for iteration; - After I calculate
mid
ask*(k+1)/2
, should I usel=mid+1
orl=mid
(and likewiser=mid-1
orr=mid
)?
Thanks!