Interview. I am looking for an algorithm that can work better than O (n ^ 2), where n is the size of the input array. (P <5000)
The questions are as follows:
Suppose we are given an array of a positive integer (let's call it a). Find out how to reorder the order of this element so that you can maximize the value of the following function:
obj = a [0] * a [1] + a [1] * a [2] + ... + a [n-2] * a [n-1] + a [n-1] * a [n ]
In addition, there is also an array of booleans (let it be called b), which is exactly the same size as an array of positive integers. If b [k] = false, this means that when we reorder an element in a positive array, we cannot move the kth elements.
Example
a = [1,2,3], b = [true, true, true]
Since all elements from b are true, we can rebuild the array however. There are six ways to re-array (for example, [1,2,3], [1,3,2], [2,1,3] ....). Below are the target function values ββfor these six devices. The location that maximizes the objective function is [1,3,2] or [2,3,1], because:
1 * 3 + 3 * 2 = 9
2 * 3 + 3 * 1 = 9
Another example:
a = [1,2,3], b = [true, false, true]
2 , - [1,2,3] [3,2,1]. .
, @shapiro.yaacov . , :
input: [1,2,4,8,16,32,64]
:
obj = 3412, [2, 8, 32, 64, 16, 4, 1]
obj = 3412, [1, 4, 16, 64, 32, 8, 2]
: [1, 10, 100, 1000]
:
obj = 110100, [1, 100, 1000, 10]
obj = 110100, [10, 1000, 100, 1]
, , - - .
, 0. , 0 . :
: [0,1,2,4,8,16,32,64]
:
obj = 3412, [2, 8, 32, 64, 16, 4, 1, 0]
obj = 3412, [0, 2, 8, 32, 64, 16, 4, 1]
obj = 3412, [1, 4, 16, 64, 32, 8, 2, 0]
obj = 3412, [0, 1, 4, 16, 64, 32, 8, 2]