Input: An array of n positive and negative numbers and a number k.
Output: Subarray of at least k consecutive elements with maximum sum of elements divided by number of elements in the subarray.
O(n^2) algorithm is easy. Does anyone have a better algorithm for this?
You can use binary search.
For a searched value
x, consider the arrayb[i] = a[i] - x. Now find the maximum sum subarray of length at leastk.This works because the average of a subarray of length
kis(a[p] + ... + a[p + k - 1]) / k. So we have:So, if you binary search for the average, by substracting it from each element, if you can find a positive-sum subarray (find the maximum one and check if it’s positive) of length at least
k, thenavgis a valid answer: continue to search in[avg, max_avg]to see if you can find a better one. If not, reduce search to[0, avg].