You are given an isosceles (a triangle with at-least two equal sides) right angle triangle with base b, we need to find the maximum number of squares of side m, which can be fitted into given triangle.
Input : b = 6, m = 2 Output : 3 Input : b = 4, m = 1 Output : 6
Let’s consider a right angle triangle XYZ, where YZ is the base of triangle. Suppose length of the base is b. If we consider the position of first square with the vertex Y, we will have (b / m-1) squares in the base, and we will be left with another isosceles right angle triangle having base length (b – m).
Let f(b, m) = Number of squares which can be fitted in triangle having base length b.
then f(b, m) = (b / m – 1) + f(b – m, m)
We can calculate f(b) using above recursion, and with use of memoization. Later we can answer each query in O(1) time. We can do it for even and odd numbers separately with the base case if (b < 2 * m) f(b, m) = 0.
The given recursion can be solved as :
f(b, m) = b / m – 1 + f(b – m, m) = b / m – 1 + (b – m) / m – 1 + f(b – 2m, m)
f(b, m) = b / m – 1 + b / m – 2 + f(b – 3m, m) +…+ f(b – (b / m)m, m)
f(b) = b / m – 1 + b / m – 2 + b / m – 3 +…..+ 1 + 0
With conditions, if (b < 2 * m) f(b, m) = 0
f(b) = sum of first (b / m – 1) natural numbers
= (b / m – 1) * (b / m) / 2
This formula can be used to reduce the time complexity upto O(1).
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer Geeks Classes Live