Leetcode 3200. Maximum Height of a Triangle
You are given an input integer N
, which represents the number of units of material you can use to build a triangle. You need to determine the maximum height of a triangle that you can construct using these units, where every additional height level i (starting from 1) requires exactly i
units to construct.
Assuming the constraints like most problems of this nature:
h
, the total number of units required will be the sum of the first h
natural numbers.
h
natural numbers: (\text{Sum} = \frac{h(h + 1)}{2})h
such that (\frac{h(h + 1)}{2} \leq N).h
:
[ h^2 + h - 2N \leq 0 ]h
will be within the range of:
[ h = \frac{-1 + \sqrt{1 + 8N}}{2} ]public class MaximumHeightOfTriangle {
public static int maximumHeight(int N) {
if (N == 0) return 0;
// Calculate the discriminant of the quadratic equation
double discriminant = 1 + 8 * (double) N;
// Calculate the positive root using the quadratic formula
double h = (-1 + Math.sqrt(discriminant)) / 2;
// The height must be an integer, so we take the floor value of h
return (int) Math.floor(h);
}
public static void main(String[] args) {
int N = 10;
System.out.println("Maximum height of a triangle with " + N + " units is: " + maximumHeight(N));
}
}
h
to comply with the integer height requirement.This approach ensures that we can efficiently find the maximum height within the constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?