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.
1class Solution {
2 public int arrangeCoins(int n) {
3 int k = 0;
4 while (n >= k + 1) {
5 k++;
6 n -= k;
7 }
8 return k;
9 }
10 public static void main(String[] args) {
11 Solution solution = new Solution();
12 int n = 8;
13 System.out.println(solution.arrangeCoins(n)); // Output: 3
14 }
15}
The method sequentially deducts coins required for each row from n, while maintaining a count of completely built rows. It makes use of a simple iterative approach.
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)
1def
The Python solution utilizes binary search to explore possible values for k, stopping at the largest k where the complete sum of first k natural numbers does not exceed n.