Shil and New Year Gift
Practice
3.9 (14 votes)
Algorithms
Approved
Bit manipulation
Dynamic programming
Medium
Open
Problem
85% Success 1423 Attempts 30 Points 5s Time Limit 256MB Memory 1024 KB Max Code

Shil wants to gift his girlfriend a new year present of N natural numbers. However, he has not decided the order in which he should give them. He wants to gifts these numbers to his girlfriend in the order having highest beauty. Beauty of sequence of N numbers A[1],A[2],A[3]...A[N] is defined as summation of GCD( A[i] , A[i+1] ) where 1 < i < = N. Beauty = summation GCD(A[i],A[i+1]) where 1 <= i < N. As being a good programmer you should help Shil to determine maximum possible beauty in any possible ordering of these numbers.Given N natural numbers,you should find the maximum beauty possible.Note that you should gift all the given numbers.You are only allowed to change the order of these numbers to calculate maximum possible beauty.

Input
First line consists of a single integer N .
Second line consists of N natural numbers

Output
Reorder these numbers in such a way a way such that beauty of sequence is maximum and output this maximum beauty possible.

Constraints
2<= N <= 15
A[i] <= 10^9

Note
GCD stands for greatest common divisor.

Please login to use the editor

You need to be logged in to access the code editor

Loading...

Please wait while we load the editor

Loading...
Results
Custom Input
Run your code to see the output
Submissions
Please login to view your submissions
Similar Problems
Points:30
31 votes
Tags:
AlgorithmsApprovedBit ManipulationDynamic ProgrammingMediumOpen
Points:30
3 votes
Tags:
Dynamic ProgrammingDynamic Programming and Bit MaskingIntroduction to Dynamic Programming 1AlgorithmsBitmask1-D
Points:30
26 votes
Tags:
AlgorithmsDynamic ProgrammingMedium