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.
1using System;
2
3public class Solution {
4 public int ArrangeCoins(int n) {
5 int k = 0;
6 while (n >= k + 1) {
7 k++;
8 n -= k;
9 }
10 return k;
11 }
12 public static void Main(string[] args) {
13 Solution solution = new Solution();
14 int n = 8;
15 Console.WriteLine(solution.ArrangeCoins(n)); // Output: 3
16 }
17}
The C# implementation uses a simple while loop to calculate how many complete rows can be constructed with n coins by deducting the number of coins needed for each successive row.
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)
1#
The C code employs long integers for intermediate calculations to avoid overflow. The binary search algorithm adjusts the search range based on whether the calculated sum of coins (for k = mid) is greater or less than n.