Solution 1: accepted 64ms 10%
|
|
Solution 2: accepted 46ms 69%
Cost of coins: 1+2+3+…+k = k(1+k)/2
Calculate the maximum of k where k(1+k) <= 2n
(0 <= k < n)
|
|
Alternative from this post12345678910111213141516171819public int arrangeCoins(int n) { //convert int to long to prevent integer overflow long nLong = (long)n; long st = 0; long ed = nLong; long mid = 0; while (st <= ed){ mid = st + (ed - st) / 2; if (mid * (mid + 1) <= 2 * nLong){ st = mid + 1; }else{ ed = mid - 1; } } return (int)(st - 1);}
Solution 3
We have many math solutions.