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 = 5The coins can form the following rows: ¤ ¤ ¤ ¤ ¤
Because the 3rd row is incomplete, we return 2.
Example 2:
n = 8The coins can form the following rows: ¤ ¤ ¤ ¤ ¤ ¤ ¤ ¤
Because the 4th row is incomplete, we return 3.
Related Topics:
Math, Binary Search
// 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;
}
};
// 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;
}
};
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;
}
};