Arranging Coins – Leetcode #441

Arranging Coins

Problem Statement

This problem is from Leetcode – Arranging Coins. The problem statement is as below:

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.

Given the integer n, return the number of complete rows of the staircase you will build.

Solution

This problem is easy enough. In awhile loop simply keep subtracting the row count from coins left. Break out of the loop when coins left is less than row count. See the code sample below:

 public int arrangeCoins(int n) {
	       
		 // the current staircase row
		 int row = 0;
		 
		 // coins left
		 int coinsLeft = n;
		 
		 while(true) {
			 
			 // subtract the row number from coins left
			 coinsLeft = coinsLeft - row;
		 	 
			 // increment row count
			 row++;
			 
			 // if coins left is less than row count then break out of the loop
			 if(coinsLeft < row) {
				 
				 break;
			 }
		 }
		 
		 return row-1;
		 
	    }

You can checkout the code from Github here: Arranging Coins. See the performance of this approach below:

Arranging Coins

See the complexity as computed by Leetcode:

One thought on “Arranging Coins – Leetcode #441

  1. I would like to thnkx for the efforts you have put in writing this web site. I’m hoping the same high-grade web site post from you in the upcoming as well. Actually your creative writing skills has inspired me to get my own web site now. Really the blogging is spreading its wings rapidly. Your write up is a great example of it.

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top