Formatted question description: https://leetcode.ca/all/441.html

441. Arranging Coins (Easy)

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/
// 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;
    }
};
// OJ: https://leetcode.com/problems/arranging-coins/
// 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/
// Time: O(1)
// Space: O(1)
class Solution {
public:
    int arrangeCoins(int n) {
        return (sqrt((long)8 * n + 1) - 1) / 2;
    }
};

Java

  • class Solution {
        public int arrangeCoins(int n) {
            int row = 0;
            while (n > row) {
                row++;
                n -= row;
            }
            return row;
        }
    }
    
  • // OJ: https://leetcode.com/problems/arranging-coins/
    // 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;
        }
    };
    
  • class Solution(object):
      def arrangeCoins(self, n):
        """
        :type n: int
        :rtype: int
        """
        return int((((1 + 8 * n) ** 0.5) - 1) / 2)
    
    

All Problems

All Solutions