Sponsored
Sponsored
This approach involves sequentially counting how many coins are required to form a complete row one row at a time. While the number of available coins is greater than or equal to coins needed for the next row, continue adding rows and reducing the count of available coins accordingly.
Time Complexity: O(√n), as the sum of the first k natural numbers grows quadratically.
Space Complexity: O(1), constant space is used.
1function arrangeCoins(n) {
2 let k = 0;
3 while (n >= k + 1) {
4 k++;
5 n -= k;
6 }
7 return k;
8}
9
10let n = 8;
11console.log(arrangeCoins(n)); // Output: 3
The approach in JavaScript employs a while loop that reduces the number of coins n by the required amount for each row, incrementing the row count k along the way.
Using a binary search, optimize the process of finding the maximum k where the sum of the first k natural numbers is less than or equal to n. Calculate mid values and determine if they result in a possible sum being less or equal to n and adjust the search space accordingly.
Time Complexity: O(log n)
Space Complexity: O(1)
1function
In JavaScript, binary search is effectively applied to track the maximum k such that the sum of first k natural numbers, represented by the mid, does not exceed n.