I have an array of mutually different elements (x_1, x_2, ..., x_n). Every element has associated a positive value (w_1, w_2, ..., w_n). The sum of these positives values is 1.
I have to find an Optimal element (x_k), which is:
and
I find this algorithm:
proc OptimalElement(arr[])
prevs_w := 0
nexts_w := 0
for (i = 0; i <= n; i++)
{
wi := arr[i].w
nexts_w := 1 - prevs_w - wi
IF (prevs_w < 0,5 && nexts_w <= 0,5) THEN
return arr[i]
ELSE
prevs_w := prevs_w + wi
ENDIF
}
end
But this algorithm compare only sum of items which index is i < k and i > k. But I need algorithm that calculate sums of items which x_i < x_k and x_i > x_k.
An Algorithm should have work with O(n) time. Do you have any idea how to solve it? Thx for tips.
Example of input:
x_i | 1 ; 4 ; 2 ; 3 ; 5
w_i | 0,1 ; 0,2 ; 0,3 ; 0,2 ; 0,2