Skip to content

Commit c95a865

Browse files
authored
Create 0441-arranging-coins.kt
1 parent 5247279 commit c95a865

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

Diff for: kotlin/0441-arranging-coins.kt

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/*
2+
* Optimized with Binary Search and Gauss summation formula: Time Complexity O(LogN) and Space Complexity O(1)
3+
*/
4+
class Solution {
5+
fun arrangeCoins(n: Int): Int {
6+
7+
var left = 1
8+
var right = n
9+
var res = 0
10+
11+
while (left <= right) {
12+
val mid = left + (right - left) / 2 //avoid a potential 32bit Integer overflow (Where left is 1 and right is Integer.MAX_VALUE)
13+
val coins = (mid.toDouble() / 2) * (mid.toDouble() + 1)
14+
if(coins > n)
15+
right = mid -1
16+
else {
17+
left = mid + 1
18+
res = maxOf(res, mid)
19+
}
20+
}
21+
22+
return res.toInt()
23+
}
24+
}
25+
26+
/*
27+
* Optimized and almost cheat-like solution (Technically not cheating) with both space and time complexity being O(1)
28+
* Here we solve for x in gauss summation formula where the result is our input variable n:
29+
* (x/2) * (x+1) = n ====> x = 1/2 * sqrt( 8n+1 ) -1 (We ignore the other possible solution since it gives us (wrong) negative x's
30+
*/
31+
class Solution {
32+
fun arrangeCoins(n: Int): Int {
33+
val x = 0.5 * Math.sqrt(8.0 * n.toDouble() + 1.0) - 1.0
34+
return Math.round(x).toInt() // round() will round up or down to nearest whole number, which we need to correctly output result
35+
}
36+
}
37+
38+
// Or if you prefer oneliner:
39+
class Solution {
40+
fun arrangeCoins(n: Int) = Math.round( 0.5 * Math.sqrt(8.0 * n.toDouble() + 1.0) - 1.0 ).toInt()
41+
}
42+
43+
44+
/*
45+
* Naive way with brute force: Time Complexity O(N) and Space Complexity O(1)
46+
*/
47+
class Solution {
48+
fun arrangeCoins(_n: Int): Int {
49+
50+
var res = 0
51+
var n = _n
52+
var step = 0
53+
54+
while( true ) {
55+
step++
56+
if(n - step < 0) return res
57+
n -= step
58+
res++
59+
}
60+
61+
return res
62+
}
63+
}

0 commit comments

Comments
 (0)