forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0441-arranging-coins.js
63 lines (52 loc) · 1.17 KB
/
0441-arranging-coins.js
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
/**
* https://leetcode.com/problems/arranging-coins/
* Linear time
* Time O(n) | Space O(1)
* @param {number} n
* @return {number}
*/
var arrangeCoins = function(n) {
let steps = 1;
let canBuild = 0;
while(n >= steps) {
n = n - steps;
canBuild++;
steps++;
}
return canBuild || 1;
};
/**
* Binary Search
* Time O(log(n)) | Space O(1)
* @param {number} n
* @return {number}
*/
var arrangeCoins = function(n) {
let left = 1;
let right = n;
let result = 0;
while(left <= right) {
const mid = Math.floor((right+left)/2);
const total = (1 + mid) * (mid/2);
if(n < total) {
right = mid -1;
} else {
left = mid+1;
result = Math.max(result, mid);
}
}
return result;
};
/**
* Math
* Time O(1) | Space O(1)
* @param {number} n
* @return {number}
*/
var arrangeCoins = function(n) {
let discriminant = 1 + 8 * n;
let sqrtDiscriminant = Math.sqrt(discriminant);
let result1 = Math.floor((-1 + sqrtDiscriminant) / 2);
let result2 = Math.floor((-1 - sqrtDiscriminant) / 2);
return Math.max(result1, result2);
};