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 of a Triangle INPUT Available Balls: red = 2 blue = 1 Triangle Structure: Row 1: 1 Row 2: 2 2 Row 3: 3 3 3 red = 2, blue = 1 ALGORITHM STEPS 1 Try Red First Row 1: Red, Row 2: Blue... 2 Try Blue First Row 1: Blue, Row 2: Red... 3 Simulate Building Subtract balls per row 4 Return Max Height Compare both approaches Simulation (Red First): Row 1: Use 1 red red=1, blue=1 Row 2: Use 2 blue FAIL! (need 2) Blue First: Row 1: 1 blue, Row 2: 2 red OK! height=2 FINAL RESULT Maximum Triangle (Height = 2): B Row 1 R R Row 2 Row 3: Not enough! Balls used: Blue: 1/1, Red: 2/2 Output: 2 Key Insight: Try both starting colors (red first OR blue first) and simulate building row by row. Odd rows use one color, even rows use the other. Return the maximum height achieved. TutorialsPoint - Maximum Height of a Triangle | Optimal Solution
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