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 maximumheight of the triangle that can be achieved.
Input: red =1, blue =1Output: 1#### Example 4Input: red =10, blue =1Output: 2Explanation:

The only possible arrangement is shown above.
To maximize the triangle’s height, we should always use the color with more balls for the larger rows. By alternating colors for each row and always picking the color with more balls for the next row, we can build the tallest triangle possible.
classSolution {
public:int maximumHeight(int red, int blue) {
int h =0, cur = red >= blue ?0:1;
int cnt[2] = {red, blue};
while (cnt[cur] >= h +1) {
cnt[cur] -= h +1;
h++;
cur ^=1;
}
return h;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
funcmaximumHeight(redint, blueint) int {
h:=0cur:=0cnt:= [2]int{red, blue}
ifblue > red {
cur = 1 }
forcnt[cur] >=h+1 {
cnt[cur] -=h+1h++cur ^= 1 }
returnh}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
publicintmaximumHeight(int red, int blue) {
int h = 0, cur = red >= blue ? 0 : 1;
int[] cnt = {red, blue};
while (cnt[cur]>= h + 1) {
cnt[cur]-= h + 1;
h++;
cur ^= 1;
}
return h;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funmaximumHeight(red: Int, blue: Int): Int {
var h = 0var cur = if (red >= blue) 0else1val cnt = intArrayOf(red, blue)
while (cnt[cur] >= h + 1) {
cnt[cur] -= h + 1 h++ cur = cur xor 1 }
return h
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defmaximumHeight(self, red: int, blue: int) -> int:
h =0 cur =0if red >= blue else1 cnt = [red, blue]
while cnt[cur] >= h +1:
cnt[cur] -= h +1 h +=1 cur ^=1return h
1
2
3
4
5
6
7
8
9
10
11
12
13
impl Solution {
pubfnmaximum_height(red: i32, blue: i32) -> i32 {
letmut h =0;
letmut cur =if red >= blue { 0 } else { 1 };
letmut cnt = [red, blue];
while cnt[cur] >= h +1 {
cnt[cur] -= h +1;
h +=1;
cur ^=1;
}
h
}
}