Arranging Coins - Math - Easy - LeetCode
💻 coding

Arranging Coins - Math - Easy - LeetCode

2 min read 399 words
2 min read
ShareWhatsAppPost on X
  • 1The problem involves arranging n coins into a staircase shape with k coins in the k-th row.
  • 2The maximum number of complete staircase rows can be calculated using a mathematical formula derived from the running sum.
  • 3The algorithm operates in constant time O(1) and requires no additional space, making it efficient.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The problem involves arranging n coins into a staircase shape with k coins in the k-th row."

Arranging Coins - Math - Easy - LeetCode

You have a total of n coins that you want to form in a staircase shape, where every k-th row must have exactly k coins.

Given n, find the total number of full staircase rows that can be formed.

n is a non-negative integer and fits within the range of a 32-bit signed integer.

Example 1:

n = 5

The coins can form the following rows: * * * * *

Because the 3rd row is incomplete, we return 2. Example 2:

n = 8

The coins can form the following rows: * * * * * * * *

Because the 4th row is incomplete, we return 3.

public class Solution {
 public int ArrangeCoins(int n) {
 return (int) ((Math.Sqrt(1 + 8.0 * n) - 1) / 2);
 }
}

Time Complexity: O(1)

Space Complexity: O(1)

Complexity Analysis Uniform cost model is used as Cost Model and n is the input number. b in this case would be 2.

Time Complexity:

Best Case O(1) : With respect to the input, the algorithm will always perform basic mathematical operation that run in constant time. Average Case O(1) : With respect to the input, the algorithm will always perform basic mathematical operation that run in constant time. Worst Case O(1) : With respect to the input, the algorithm will always perform basic mathematical operation that run in constant time. Auxiliary Space:

Worst Case O(1) : No extra space is used. Algorithm Approach: Mathematics

The problem is basically asking the maximum length of consecutive number that has the running sum lesser or equal to n. In other word, find x that satisfy the following condition:

1 + 2 + 3 + 4 + 5 + 6 + 7 + ... + x <= n sum_{i=1}^x i <= n Running sum can be simplified,

(x * ( x + 1)) / 2 <= n Using quadratic formula, x is evaluated to be,

x = 1 / 2 * (-sqrt(8 * n + 1)-1) (Inapplicable) or x = 1 / 2 * (sqrt(8 * n + 1)-1) Negative root is ignored and positive root is used instead. Note that 8.0 * n is very important because it will cause Java to implicitly autoboxed the intermediate result into double data type. The code will not work if it is simply 8 * n. Alternatively, an explicit casting can be done 8 * (long) n).

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 1 October 2020 · 2 min read · 399 words

Part of AskGif Blog · coding

You might also like

Arranging Coins - Math - Easy - LeetCode | AskGif Blog