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