Arranging Coins
1 min read

Arranging Coins

Arranging Coins

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.

Example:

n = 5

The coins can form the following rows:
¤
¤ ¤
¤ ¤

Because the 3rd row is incomplete, we return 2.

Solution

Actually, this is the math problem.

The sum of length of each row of staircase shape is n(n + 1) / 2. So this question is to solve the inequality x² + x - 2n <= 0.

Use the formula : x = (-b +/- sqrt(b² - 4ac)) / 2a

The final answer will be x = sqrt(2*n + 0.25) - 0.5

import kotlin.math.sqrt
fun arrangeCoins(n: Int): Int {
     return (sqrt(2 * n.toLong() +0.25) - 0.5).toInt()
    }


Enjoying these posts? Subscribe for more