Skip to content

Files

Latest commit

Jul 2, 2020
e130f40 · Jul 2, 2020

History

History
This branch is 2352 commits behind lzl124631x/LeetCode:master.

441. Arranging Coins

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
Jul 2, 2020

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.

Related Topics:
Math, Binary Search

Solution 1. Brute Force

// OJ: https://leetcode.com/problems/arranging-coins/
// Author: github.com/lzl124631x
// Time: O(sqrt(N))
// Space: O(1)
class Solution {
public:
    int arrangeCoins(int n) {
        long i = 1, sum = 0;
        while (sum + i <= n) sum += i++;
        return i - 1;
    }
};

Solution 2. Binary Search

// OJ: https://leetcode.com/problems/arranging-coins/
// Author: github.com/lzl124631x
// Time: O(logN)
// Space: O(1)
class Solution {
public:
    int arrangeCoins(int n) {
        int L = 1, R = n;
        while (L <= R) {
            long M = L + (R - L) / 2, sum = M * (1 + M) / 2;
            if (sum == n) return M;
            if (sum < n) L = M + 1;
            else R = M - 1;
        }
        return R;
    }
};

Solution 3. Math

x * (x + 1) / 2 <= n

x^2 + x - 2n <= 0

x <= (sqrt(8n + 1) - 1) / 2
// OJ: https://leetcode.com/problems/arranging-coins/
// Author: github.com/lzl124631x
// Time: O(1)
// Space: O(1)
class Solution {
public:
    int arrangeCoins(int n) {
        return (sqrt((long)8 * n + 1) - 1) / 2;
    }
};