[LeetCode] Arranging Coins

441. Arranging Coins

You have n coins and you want to build a staircase with these coins. The staircase consists of k rows where the ith row has exactly i coins. The last row of the staircase may be incomplete.

Given the integer n, return the number of complete rows of the staircase you will build.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public:
int arrangeCoins(int n) {
long long res = 0, l = 0, r = INT_MAX;

while(l <= r) {
long long m = l + (r - l) / 2;
long long sum = m * (m + 1) / 2;
if(sum <= n) res = max(res, m);

if(sum <= n) l = m + 1;
else r = m - 1;
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/06/PS/LeetCode/arranging-coins/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.