2

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?

9
  • 2
    This looks more like a highest average subarray problem. Very similar. Commented Oct 26, 2012 at 20:07
  • Does the subarray have to be consecutive or are you looking for a subset? Commented Oct 26, 2012 at 20:09
  • 1
    This question has a trivial answer: just find the maximal element of the array. A one-element sub-array, containing this element is the maximum sum/size sub-array. Commented Oct 26, 2012 at 20:21
  • @EvgenyKluev Not true. Are you forgetting "negative" values? Commented Oct 26, 2012 at 20:30
  • @Wug do you have a link for "highest average subarray" problem? Commented Oct 26, 2012 at 20:32

1 Answer 1

3

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].

Sign up to request clarification or add additional context in comments.

2 Comments

Makes sense. The runtime order becomes O(N)*log(range of numbers). It's still not clear for me when to stop the binary search.
@MohammadMoghimi - you can stop it when the interval you're searching in becomes small enough for your purposes. Try stopping it when it becomes smaller than 10^-3 for example. If it's not good enough, decrease the exponent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.