+ 2

Subsequence with highest average

Given a sequence of N nonnegative numbers, how to find efficiently the continuous subsequence of length at least L (L is in input) with the highest possible average (sum of elements in the subsequence divided by its length)? Please no brute-force algorithms trying all options. Example: 0,9,8,1,9,5,2,3 L=3 result: 9,8,1,9 average=6.75 Thanks for help.

13th Jan 2018, 4:24 PM
michal
4 odpowiedzi
+ 3
I am not sure you can do better than N*L ... Maybe you could search on the internet, there are some forums with algorithms addict :)
14th Jan 2018, 10:33 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 2
It seems like you need it, maybe for class. What did you tried to do ?
14th Jan 2018, 7:19 AM
Baptiste E. Prunier
Baptiste E. Prunier - avatar
+ 2
I tried for each possible length K from L to 2*L-1 (longer subsequences can be divided into two parts) to find the sum and average of first K elements, then by adding K+1. element and subtracting first element find the sum and average of next K elements, and so on for all K consecutive elements, keeping the maximum average found. But that's slow - complexity is O(N*L).
14th Jan 2018, 9:40 AM
michal
+ 1
ok, thank you for trying to help
15th Jan 2018, 9:39 AM
michal