We have N coins which need to arrange in form of a triangle, i.e. first row will have 1 coin, second row will have 2 coins and so on, we need to tell maximum height which we can achieve by using these N coins. Examples:
Input : N = 7
Output : 3
Explanation: Maximum height will be 3, putting 1, 2 and then 3 coins. It is not possible to use 1 coin left.Input : N = 12
Output : 4
Explanation: Maximum height will be 4, putting 1, 2, 3 and 4 coins, it is not possible to make height as 5, because that will require 15 coins.
Brute-Force Approach:
A triangle takes coins in increasing order i.e., first line will have 1 coin, second line will have 2 coins and so on.
So we can subtract [1.2.3.,,,] till n is greater than the number, and increment our answer.
Below is the implementation of the above approach:
def triangle(input1):
if input1 < 1 :
return 'Zero'
else :
# Counter for controlling the coins in a row
a = 1 height = 0
while input1 > 0 :
if input1 - a > = 0 :
input1 = input1 - a
a = a + 1
height = height + 1
else :
break
return height
if __name__ = = "__main__" :
testinput1 = 22
print (triangle(testinput1))
|
6
Time complexity: O(sqrt(n))
Auxiliary space: O(1).
Efficient Approach: This problem can be solved by finding a relation between height of the triangle and number of coins. Let maximum height is H, then total sum of coin should be less than N,
Sum of coins for height H <= N H*(H + 1)/2 <= N H*H + H – 2*N <= 0 Now by Quadratic formula (ignoring negative root) Maximum H can be (-1 + √(1 + 8N)) / 2 Now we just need to find the square root of (1 + 8N) for which we can use Babylonian method of finding square root
Below code is implemented on above stated concept
# Python3 program to find # maximum height of arranged # coin triangle # Returns the square root of n. # Note that the function def squareRoot(n):
# We are using n itself as
# initial approximation
# This can definitely be improved
x = n
y = 1
e = 0.000001 # e decides the accuracy level
while (x - y > e):
x = (x + y) / 2
y = n / x
return x
# Method to find maximum height # of arrangement of coins def findMaximumHeight(N):
# calculating portion inside the square root
n = 1 + 8 * N
maxH = ( - 1 + squareRoot(n)) / 2
return int (maxH)
# Driver code to test above method N = 12
print (findMaximumHeight(N))
# This code is contributed by # Smitha Dinesh Semwal |
4
Time complexity: O(log N)
Auxiliary space: O(1)
Please refer complete article on Maximum height when coins are arranged in a triangle for more details!