![]() |
VOOZH | about |
Given N coins, the task is to arrange them in a triangular pattern i.e the first row having 1 coin, the second row 2 coins, and so on. The goal is to the maximum height of the triangle that can be formed using all or or some of the coins.
For Example:
Input: N = 7 -> Output: 3
Input: N = 12 -> Output: 4
Let's explore different methods to find maximum height when coins are arranged in Triangle.
In this method, we derive the height H using the mathematical relation
H ∗ (H+1)/2 ≤ N
Solving this gives:
This method avoids loops and gives the result in constant time.
4
Explanation: math.sqrt(1 + 8 * N) calculates the square root part of the quadratic formula. We then compute (-1 + sqrt(...)) / 2 to get the maximum possible height and convert it to an integer.
Instead of linearly subtracting, we can apply binary search to find the maximum H such that
H ∗ (H+1)/2 ≤ N
It’s faster for large inputs than the iterative approach.
4
Explanation:
This approach starts from 1 and subtracts increasing coin counts (1, 2, 3, ...) until we run out of coins. It’s simple and easy to understand but less efficient for large N.
6
Explanation:
Please refer complete article on Maximum height when coins are arranged in a triangle for more details!