This question was asked to me in an interview, and I was unable to come up with an optimal solution.
Question
Given an even size array, we can perform any operation on the array, until the array becomes empty such that the overall cost should be minimum.
Operations:
- remove first and last element => cost will be gcd(first, last)
- remove first and middle element => cost will be gcd(first, middle)
- remove middle and last element => cost will be gcd(middle, last)
Note:
- In an even size array, there are two middle elements. So, consider the second middle element as the middle element.
- gcd(x,y) stands for Greatest Common Divisor between x and y
Example:
Input: [2, 4, 8, 6]
Output: 4
Explanation:
- In the first operation remove the first and middle element, cost = gcd(2,8) = 2
- In the second operation remove 4 and 6, cost = gcd(4,6) = 2
- Total cost = 2+2 = 4