The three crystals
- O(n log n) · Hard
- Full plan
- Python
- JavaScript
- lists
- sorting
- operations
Problem
"Three crystals, not one more," the sorceress warns you at the last door. The spell that opens it fuses three crystals from your inventory, and its power is the product of their charges.
Write a function that takes charges, a list of integers with at least three elements, and returns an integer: the largest product you can get by multiplying three of them. Each crystal is used once, but two different crystals may have the same charge.
With [4, 1, 7, 2] you pick 4, 7 and 2, and the power is 4 × 7 × 2 = 56. Careful: some crystals are cursed, with a negative charge, and some have charge 0. A negative times a negative is positive. If every choice gives a negative power, return the least bad one, the closest to 0.
Examples
The one from the example
[4, 1, 7, 2] → 56
Exactly three crystals
[3, 5, 2] → 30
A cursed one that doesn't help
[-10, 1, 2, 3] → 6
Two cursed ones that fall short
[-1, -2, 4, 5, 6] → 120
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def max_power(charges):
passJavaScript
function maxPower(charges) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.