Python Program for Maximum Height when Coins are Arranged in a Triangle (original) (raw)

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.

Using Direct Mathematical Formula

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.

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:

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:

Please refer complete article on Maximum height when coins are arranged in a triangle for more details!