-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharrangingCoins.ts
More file actions
56 lines (44 loc) · 1.51 KB
/
Copy patharrangingCoins.ts
File metadata and controls
56 lines (44 loc) · 1.51 KB
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
/*
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.
Example 1:
Input: n = 5
Output: 2
Explanation: Because the 3rd row is incomplete, we return 2.
Example 2:
Input: n = 8
Output: 3
Explanation: Because the 4th row is incomplete, we return 3.
*/
function arrangeCoins(n: number): number {
// At the kth rows, we will have the maximum total is k*(k+1) coins
// So to find the rows, we just need to find the number k that satisfies the condition k*(k+1)/2 >= n
// If k*(k+1)/2 = n, then return k
// And if k*(k+1)/2 > n, then return k - 1, because row kth is not completed
// We can use binary search since the k in the array from 1 to n (it is sorted array)
// Time complexity: O(log(n))
// Space complexity: O(1)
let left = 1;
let right = n;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
let temp = (mid * (mid + 1)) / 2;
if (temp === n) {
return mid;
}
if (temp < n) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return left - 1;
// Approach 2
// Using math for calculate
// k * (k + 1) / 2 <= n (n > 0)
// <=> k^2 + k - 2n <= 0
// <=> k <= (-1 + √(1 + 8n)) / 2 (Using the quadratic formula k = (-b ± √(b² - 4ac)) / 2a, where a = 1, b = 1, and c = -2n)
// return Math.floor((-1 + Math.sqrt(1 + 8 * n)) / 2);
}
console.log(arrangeCoins(1));