Skip to main content
Back to problems
#3200
Easy Algorithms

Maximum height of a triangle

Array Enumeration
44.2% acceptance
Feb 25, 2026
165
30
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.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn max_height_of_triangle(red: i32, blue: i32) -> i32 {
    // Try both: red starts (rows 1,3,5,...) and blue starts (rows 1,3,5,...)
    let try_start = |mut a: i32, mut b: i32| -> i32 {
      // a takes odd rows (1,3,5,...), b takes even rows (2,4,6,...)
      let mut h = 0;
      let mut row = 1;
      loop {
        if row % 2 == 1 {
          if a >= row { a -= row; h += 1; } else { break; }
        } else {
          if b >= row { b -= row; h += 1; } else { break; }
        }
        row += 1;
      }
      h
    };
    try_start(red, blue).max(try_start(blue, red))
  }
}