See the original problem on HackerRank.
Solutions
This problem simulates the situation when you need some additional “domain knowledge” to find a solution. In this case the domain is “geometry” and you have to find (or recall) the Triangle inequality:
for any triangle, the sum of the lengths of any two sides must be greater than or equal to the length of the remaining side
In other terms, for any three sticks \(a, b, c\), the following must be true:
\( a > b + c\) \( b > a + c\) \( c > a + b\)
Since we want the maximum perimeter triangle, we can sort the sticks in descending order and check for each triple of adjacent sticks if the inequality is verified:
|
|
Note that we only check:
\( b + c > a\)
since:
\( a > b > c\)
If the former is verified, we know that:
\( a + c > b\)
since \( a > b\)
And \( a + b > c\)
since \( a > c\)
The final cost is \( O(N \cdot log N) \).
Here is a fluent solution in Python:
|
|