Maximum Height of a Triangle - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: red = 2, blue = 1
Output: 2
💡 Note: Start with red (row 1: 1 red ball), then blue (row 2: 2 blue balls, but we only have 1). So we can't complete row 2 with blue. If we start with blue (row 1: 1 blue ball), then red (row 2: need 2 red balls, we have 2), we get height 2.
Example 2 — Equal Balls
$ Input: red = 1, blue = 1
Output: 1
💡 Note: We can only build 1 row using either color. Row 2 would need 2 balls but we only have 1 of the other color.
Example 3 — Larger Input
$ Input: red = 10, blue = 1
Output: 2
💡 Note: Start with blue (row 1: 1 blue ball), then red (row 2: 2 red balls). We have enough red balls but can't continue to row 3 which would need 3 blue balls.

Constraints

  • 1 ≤ red ≤ 100
  • 1 ≤ blue ≤ 100

Visualization

Tap to expand
Maximum Height Triangle ProblemInput: red=2, blue=1RRBTriangle RulesRow 1: 1 ballRow 2: 2 ballsRow 3: 3 balls...Adjacent rows: different colorsBest Arrangement122Height: 2Strategy: Try both blue-first and red-first patternsBlue first: Row 1 (1 blue) + Row 2 (2 red) = Height 2 ✓Red first: Row 1 (1 red) + Row 2 (2 blue, but only have 1) = Height 1Output: max(2, 1) = 2
Understanding the Visualization
1
Input
Two integers: red balls and blue balls
2
Build Triangle
Each row needs i balls, adjacent rows different colors
3
Find Maximum
Try both starting colors, return max height
Key Takeaway
🎯 Key Insight: Always try both starting colors since one arrangement might be significantly better than the other
Asked in
Microsoft 15 Google 12
23.4K Views
Medium Frequency
~15 min Avg. Time
856 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