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
You can use Quickselect:
The problem here is the run time is O(n²) in the worst case. However, it is O(n) on average (assuming the elements are somewhat evenly distributed). There are other partition-based selection algorithms with deterministic linear time which you can probably adapt in a similar way, but they are more complicated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With