PU Arranging Coins

Jan 01, 1970

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.
  • n = 8
    • The coins can form the following rows:
    • ¤
    • ¤ ¤
    • ¤ ¤ ¤
    • ¤ ¤
    • Because the 4th row is incomplete, we return 3.

C Solution 1:

int arrangeCoins(int n) {
    int i = 1;
    while (n >= i) {
        n -= i++;
    }
    return i - 1;
}

C Solution 2:

int arrangeCoins(int n) {
    int l = 1, r = n;
    while (l <= r) {
        int m = l + (r - l) / 2;
        if (0.5 * m * m + 0.5 * m <= n) {
            l = m + 1;
        }
        else r = m - 1;
    }
    return l - 1;
}

C Solution 3:

int arrangeCoins(int n) {
    return sqrt(2.0 * n + 0.25) - 0.5;
}

Summary:

  1. 22ms, 42.06%
  2. Binary search is strange, because of double?

LeetCode: 441. Arranging Coins