LeetCode Problem - Link
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.
Example 1:
Input: red = 2, blue = 4
Output: 3
Sequential Solution
I created a helper function that takes in the first and second color arguments respectively, which can calculate and return the max size of the tree that can be constructed based on which colored ball is first.
We compare both scenarios, choose the one that has the highest size, and return it
/** * @param {number} red * @param {number} blue * @return {number} */ var maxHeightOfTriangle = function (red, blue) { let sizeBlueFirst = calcMaxSize(blue,red) let sizeRedFirst = calcMaxSize(red,blue) let max = sizeBlueFirst if(sizeRedFirst>max){ max = sizeRedFirst } return max }; const calcMaxSize = (first,second) => { var size = 0; for (var i = 1; ; i++) { var isEven = i % 2 == 0 if (!isEven) { first -= i; } if (isEven) { second -= i } if (first < 0 || second < 0) { break } size += 1 } return size }