Arranging Coins

Problem

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 1:

n = 5

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

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

n = 8

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

Because the 4th row is incomplete, we return 3.

Solution

General Exhaustive Solution (brute force) using Iteration: O(n)

public class Solution {
    public int arrangeCoins(int n) {
        int res = 0;
        int coins = 1;
        while (n >= coins) {
            n -= coins++;
            res++;
        }
        return res;
    }
}

Using Gauss's Formula in a Opposite Way: O(1)

public class Solution {
    public int arrangeCoins(int n) {
        return (int)((-1 + Math.sqrt(1 + 8 * (long)n)) / 2);
    }
}

Analysis

The first solution is pretty straightforward
The second solution applies Gauss's counting formula very smartly
When we finish arranging coins, the total numbers would be 1 + 2 + 3 + ...
The last number is the res we need to return, and we know the total sum by using Gauss's Formula
1 + 2 + 3 + .. + res = n
(1 + res) * res / 2 = n
res^ 2 + res - 2 * n == 0
Then we just need to solve this equation, which is the return statement does there

results matching ""

    No results matching ""