-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathMaximumHeightOfATriangle.java
More file actions
31 lines (26 loc) · 970 Bytes
/
MaximumHeightOfATriangle.java
File metadata and controls
31 lines (26 loc) · 970 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// https://leetcode.com/problems/maximum-height-of-a-triangle
// T: O(log(n) + log(m))
// S: O(1)
public class MaximumHeightOfATriangle {
public static int maxHeightOfTriangle(int red, int blue) {
return Math.max(possibleRows(red, blue), possibleRows(blue, red));
}
private static int possibleRows(int oddRowBalls, int evenRowBalls) {
final int evenRows = possibleEvenRows(evenRowBalls);
final int oddRows = possibleOddRows(oddRowBalls);
return Math.min(oddRows, evenRows + 1) + Math.min(oddRows, evenRows);
}
private static int possibleOddRows(int balls) {
return (int) Math.sqrt(balls);
}
/*
k - (-1 + sqrt(1 + 4b)) / 2 = 0
k = (-1 + sqrt(1 + 4b)) / 2
*/
private static int possibleEvenRows(int balls) {
return (int) ((Math.sqrt(1 + 4 * balls) - 1) / 2);
}
public static void main(String[] args) {
System.out.println(maxHeightOfTriangle(10, 1));
}
}