Greedy · Hard
376. Arranging Amplifiers
Topics: Greedy, Sorting, Math
Solve it on DeVert Campus - free code runner
Problem
You have n amplifiers, each loaded with a positive integer value. Wired one after another, an amplifier loaded with value Y that receives an incoming signal of strength X outputs a signal of strength Y^X (Y to the power X); the first amplifier in the chain receives an initial signal of strength 1. Find the arrangement (order to wire the amplifiers, from first/innermost to last/outermost) producing the strongest possible final signal, and print the amplifier values in that order, space-separated. (Classic SPOJ 'ARRANGE' problem; test data is kept small enough that the optimal order is unique.)
Input and output
Input: The first line contains an integer n, the number of amplifiers. The second line contains n space-separated integers, the amplifier values.
Output: Print the amplifier values in the optimal wiring order (first/innermost to last/outermost), space-separated.
Example
Input: 3 5 6 4 Output: 6 5 4
Constraints
1 <= n <= 8, 1 <= value <= 9
Key observation
This is a rare example where a 'greedy' rule has KNOWN, documented mathematical exceptions (the 1's-first rule, and the 2-vs-3 special case) - a reminder that greedy heuristics should always be verified rigorously, not just assumed correct from a plausible-sounding general principle.
Intuition
Arrange amplifiers in a chain to produce the strongest possible final power-tower signal, where each amplifier raises the incoming signal to its own loaded power.
Brute force: Try every possible permutation of the n amplifiers (n! orderings) and compute the exact resulting power tower for each, comparing them directly with big-integer arithmetic - given the tiny constraint (n<=8), this is actually a perfectly viable, safe approach to fall back on.
Optimised: A pairwise comparison rule (which of two orderings, A-then-B or B-then-A, gives a bigger result) lets you sort amplifiers directly by this custom comparator - but the specific mathematical exceptions (handling 1's specially, and the well-known 2-versus-3 edge case) must be incorporated into the comparator correctly, or the general 'bigger first' heuristic alone will occasionally give the wrong order.
Exact Integer Comparator Sort
Use the same pairwise comparator idea, deciding the relative order of two amplifier values a and b by comparing a^b against b^a, but since the constraints guarantee small values (at most 9) and a short chain (at most 8 amplifiers), compute both sides of that comparison as exact integers (no larger than 9^9, which fits comfortably in a 64-bit integer) rather than using floating-point logarithms. This gives the same fast comparator-based sort as before but with no risk of precision error, guaranteeing the unique optimal arrangement the problem promises is found exactly.
Time: O(n log n)
Space: O(1)
Log-Based Pairwise Comparator Sort
Instead of testing every full ordering, use the fact that swapping two adjacent amplifiers only affects the exponent tower locally at those two positions: an exchange argument gives a total order by comparing, for two values a and b, whether b*ln(a) is greater than a*ln(b) (equivalently comparing a^b to b^a using logarithms to keep numbers manageable), and placing whichever value wins this comparison later in the chain. Sorting all n amplifiers with this pairwise comparator produces the arrangement directly. Using floating-point logarithms makes each comparison fast, though it introduces a small risk of precision errors when two values are very close under this comparison.
Time: O(n log n)
Space: O(n)
Try Every Permutation
Since n is at most 8, generate every one of the n! possible orderings of the amplifiers, and for each ordering simulate the chain: start with a running signal of 1, and for each amplifier in the chosen order raise the running signal to the power of that amplifier's value, feeding the result into the next amplifier. Track which complete ordering produces the largest final signal, comparing via logarithms internally since power towers even for values up to 9 grow far beyond ordinary integer ranges. Because it tries literally every arrangement, this is guaranteed correct but is only tractable because n is tiny.
Time: O(n! * n)
Space: O(n)
Step by step
1. In general, place LARGER values EARLIER (closer to the start of the chain) - compare two candidates for adjacent placement by which order produces the bigger resulting power tower.
2. Watch for two special exceptions: amplifiers loaded with 1 contribute the LEAST when placed early (1 raised to anything is always 1), so place any 1's FIRST, not according to the general rule; and the specific pair of values 2 and 3 is a well-known exception to the 'bigger first' rule (3 before 2 sometimes beats 2 before 3, or vice versa, contrary to naive expectation).
3. For inputs this small, directly comparing candidate orderings with big-integer arithmetic double-checks the reasoning.
Complexity
Time: O(n log n) with a correct custom comparator-based sort; O(n! * n) if verifying via brute-force permutation checking, which remains entirely feasible given n<=8.
Space: O(n), for the resulting ordering.
Edge cases
amplifiers loaded with the value 1 (best placed first, since 1 to any power is 1), the specific pair of values 2 and 3 together (a known exception to the 'bigger first' rule), and n at its maximum of 8 to confirm every ordering comparison is handled correctly.
Interview tip
Be ready to mention that given the tiny constraint (n<=8), brute-force permutation checking with big-integer comparison is a genuinely SAFE fallback if you're not 100% certain of every exception in the comparator-based greedy rule - a good pragmatic engineering call when correctness matters more than elegance.