![]() |
VOOZH | about |
What is the maximum number of squares of size 2x2 units that can be fit in a right-angled isosceles triangle of a given base (in units).
A side of the square must be parallel to the base of the triangle.
Examples:
Input : 8
👁 Image
Output : 6
Explanation: We get total 6 squares ( 1 + 2 + 3). Please refer the below diagram.Input : 7
Output : 3
For an isosceles triangle, the base is equal to the height. To accommodate a triangle in the diagonal, we need an extra 2 units for both the height and base (for example, the CF and AM segments in the above diagram do not contribute to any square).
In the remaining length of the base, we can fit (length - 2)/2 squares since each square has a side of 2 units. This same logic applies to the height, so no further calculation is needed there.
So, for each level of given length we can construct "(length-2)/2" squares. This gives us a base of "(length-2)" above it. Continuing this process to get the no of squares for all available "length-2" height, we can calculate the squares.
while length > 2
answer += (length - 2 )/2
length = length - 2For more effective way, we can use the formula of sum of AP n * ( n + 1 ) / 2, where n = length - 2
Output:
6Time complexity : O(1)
Auxiliary Space : O(1)