Maximum Height of a Triangle - Problem

Imagine you're building a colorful ball pyramid! You have red and blue colored balls, and you want to stack them into a triangle where:

  • The 1st row has 1 ball
  • The 2nd row has 2 balls
  • The 3rd row has 3 balls
  • And so on...

Rules:

  • All balls in the same row must be the same color
  • Adjacent rows must have different colors

Given the count of red and blue balls, return the maximum height of the triangle you can build!

Example: With 2 red and 4 blue balls, you could build:
Row 1: 1 red ball
Row 2: 2 blue balls
Row 3: 3 red balls (but you only have 1 red left!)
So maximum height is 2.

Input & Output

example_1.py β€” Basic Case
$ Input: red = 2, blue = 4
β€Ί Output: 3
πŸ’‘ Note: Starting with blue: Row 1 (1 blue), Row 2 (2 red), Row 3 (3 blue). Total height = 3. Starting with red only gives height 2.
example_2.py β€” Equal Balls
$ Input: red = 4, blue = 9
β€Ί Output: 3
πŸ’‘ Note: Best pattern: Row 1 (1 red), Row 2 (2 blue), Row 3 (3 red). Uses 4 red and 2 blue balls. Height = 3.
example_3.py β€” Minimum Case
$ Input: red = 1, blue = 1
β€Ί Output: 1
πŸ’‘ Note: Can only build 1 row with either 1 red ball or 1 blue ball. Height = 1.

Constraints

  • 1 ≀ red, blue ≀ 100
  • Adjacent rows must have different colors
  • All balls in the same row must be the same color

Visualization

Tap to expand
πŸŽͺ Carnival Ball Stacking ChallengeRed: 2 balls, Blue: 4 balls - Build the tallest pyramid!πŸ”΄ Pattern 1: Start RedRow 1: 1 RedRow 2: 2 BlueRow 3: Need 3 Red (only have 1 left)Height: 2 βŒπŸ”΅ Pattern 2: Start Blue ✨Row 1: 1 BlueRow 2: 2 RedRow 3: 3 BlueπŸ† WINNER!Max Height: 3πŸ’‘ Key InsightSince colors must alternate, there are only 2 possible patterns to try!
Understanding the Visualization
1
πŸ”΄ Try Red First
Start with red balls in row 1, then blue in row 2, red in row 3...
2
πŸ”΅ Try Blue First
Start with blue balls in row 1, then red in row 2, blue in row 3...
3
πŸ“ Compare Heights
Both approaches will give different heights - pick the maximum!
4
πŸ† Optimal Solution
The winning pattern gives us the tallest possible pyramid
Key Takeaway
🎯 Key Insight: The alternating color constraint means we only need to check 2 scenarios - starting with red or starting with blue!
Asked in
Google 15 Amazon 12 Meta 8 Apple 6
28.4K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
πŸ’‘ Explanation
AI Ready
πŸ’‘ Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen