0

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 that k*(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 and a[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:

  1. I am unsure if this will give me the maximum value of k;
  2. Should I continue the iteration while(l<r) or while(l<=r)? l and r are the usual two pointers used for iteration;
  3. After I calculate mid as k*(k+1)/2, should I use l=mid+1 or l=mid (and likewise r=mid-1 or r=mid)?

Thanks!

1 Answers1

0

You are making the problem way too complexed, logically all you need to do is this:

int number = n; //the number you are getting
int index = 0;
int iteration = 0;
while(index <= number){
    iteration++;
    index += iteration;
}
return iteration; //this will be the maximum complete level, the code is incomplete but this sounds like an assignment so good luck!!

For a more effiecient solution you can use Guass's formula for summing up numbers for example to sum up the numbers 1-100 you can do the following: 101*100/2 or (n+1)*n/2.. So if you are comfortable you can:

int number = n; //the number you are getting
double iteration = sqrt(number/2.0)*2;//remember to add the brackets 
                                      //inside.
if(iteration - Math.floor(iteration) >= 0.5)return iteration + 1;
else return iteration;

If there are any errors feel free to correct me...

Yunfei Chen
  • 630
  • 1
  • 8
  • 20