We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Maximum Height of a Triangle

Difficulty: Easy


Problem Description

You are given two integers red and blue representing the count of red and blue colored balls. You have to arrange these balls to form a triangle such that the 1st row will have 1 ball, the 2nd row will have 2 balls, the 3rd row will have 3 balls, and so on. All the balls in a particular row should be the same color, and adjacent rows should have different colors. Return the maximum height of the triangle that can be achieved.


Key Insights

  • The height of the triangle is determined by the number of rows that can be formed with alternating colors.
  • The number of balls required to form a triangle of height h is the sum of the first h natural numbers, which is given by the formula: h * (h + 1) / 2.
  • To maximize the height, we need to ensure that both colors can sustain the required number of balls for each row.

Space and Time Complexity

Time Complexity: O(sqrt(n)), where n is the total number of balls available. Space Complexity: O(1), as we are using a constant amount of space.


Solution

To solve the problem, we can use a simple iterative approach to determine the maximum height of the triangle. We will:

  1. Calculate the total number of balls available (red + blue).
  2. Iterate through possible heights, checking if we can form the required number of balls for each height with the available colors.
  3. Ensure that the number of balls for the current height (h * (h + 1) / 2) can be distributed between the two colors in a way that satisfies the color constraints.

Code Solutions

def maxHeight(red, blue):
    total_balls = red + blue
    height = 0
    
    while (height + 1) * (height + 2) // 2 <= total_balls:
        height += 1
    
    return height
← Back to All Questions