
Problem Statement
This problem is from Leetcode – Arranging Coins. The problem statement in short is as below:
Given n coins, return the number of complete rows in a staircase where the ith row has i coins.
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:
PERFORMANCE ANALYSIS
| RUNTIME | 5 ms | Beats 47.75 % |
| MEMORY | 40.78 MB | Beats 93.38 % |
| TIME COMPLEXITY | O(Sqrt (N) ) |
Leave a Reply