Mohammad Moghimi
Mohammad Moghimi

Reputation: 4696

Finding subarray with maximum sum/number of elements

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?

Upvotes: 2

Views: 3065

Answers (1)

IVlad
IVlad

Reputation: 43517

You can use binary search.

For a searched value x, consider the array b[i] = a[i] - x. Now find the maximum sum subarray of length at least k.

This works because the average of a subarray of length k is (a[p] + ... + a[p + k - 1]) / k. So we have:

(a[p] + ... + a[p + k - 1]) / k >= avg
a[p] + ... + a[p + k - 1] >= avg * k
(a[p] - avg) + ... + (a[p + k - 1] - avg) >= 0

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, then avg is 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].

Upvotes: 3

Related Questions