#3200

Maximum Height of a Triangle

Easy
ArrayEnumerationGreedyEnumeration
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of simulating each row, we can calculate the maximum height directly by determining how many complete rows we can form with the available balls. This is done by checking both configurations (red on top and blue on top) and taking the maximum.

⚙️

Algorithm

3 steps
  1. 1Step 1: Define a function to calculate the maximum height for a given top color.
  2. 2Step 2: Use a loop to calculate how many rows can be formed until we run out of balls.
  3. 3Step 3: Compare the heights obtained from both configurations and return the maximum.
solution.py11 lines
1def maxHeight(red, blue):
2    def calculate_height(r, b):
3        height = 0
4        while r >= height + 1 or b >= height + 1:
5            height += 1
6            if height % 2 == 1:
7                r -= height
8            else:
9                b -= height
10        return height
11    return max(calculate_height(red, blue), calculate_height(blue, red))

Complexity note: The time complexity is O(n) because we are iterating through the number of rows we can build until we run out of balls, which is linear with respect to the maximum height.

  • 1The arrangement must alternate colors, which limits how many rows can be formed.
  • 2The maximum height is determined by the color with the fewer balls when alternating.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.