Python Program for Maximum Height when Coins are Arranged in a Triangle
Last Updated :
31 Oct, 2025
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:
H = \frac{-1 + \sqrt{1 + 8N}}{2}
This method avoids loops and gives the result in constant time.
Python
import math
N = 12
H = int((-1 + math.sqrt(1 + 8 * N)) / 2)
print(H)
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.
Using Binary Search
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.
Python
N = 12
low, high = 0, N
h = 0
while low <= high:
mid = (low + high) // 2
coins = mid * (mid + 1) // 2
if coins <= N:
h = mid
low = mid + 1
else:
high = mid - 1
print(h)
Explanation:
- low and high define the search range.
- mid represents a possible height.
- If mid forms fewer coins than available, increase low; else decrease high.
- When the loop ends, h gives the highest valid height.
Using Iterative Subtraction
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.
Python
N = 22
a = 1
h = 0
while N > 0:
if N - a >= 0:
N -= a
a += 1
h += 1
else:
break
print(h)
Explanation:
- a tracks the number of coins needed for the current row.
- Coins are subtracted from N in each iteration.
- When coins are insufficient for the next row, the loop stops, and height gives the total number of complete rows formed.
Please refer complete article on Maximum height when coins are arranged in a triangle for more details!
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice