2

Suppose there's an integer array arr[0..n-1]. Find a subsequence sub[i..j] (i > 0 and j < n - 1) such that the rest of the array has the smallest average.

Example:

arr[5] = {5,1,7,8,2};

Remove {7,8}, the array becomes {5, 1, 2} which has average 2.67 (smallest possible).

I thought this is a modification of the Longest Increasing Subsequence but couldn't figure it out.

Thanks,

user3813674
  • 2,193
  • 1
  • 11
  • 23
  • 1
    You'll need to define the length of the subsequence or the minimum number of elements left, as well. For example, a better solution to your example is to remove `{5, 1, 7, 8}` and get an average of 2 (only one element). However, if you're requiring that the resulting array needs two or more elements, then it isn't a solution. – Joe Kington Jan 17 '16 at 01:30
  • I forgot the conditions for i and j. Thanks for pointing it out. – user3813674 Jan 17 '16 at 01:40
  • That still doesn't sound right. `{1}` has an average of `1`, where `i = 1`, `j = 1`, `1 > 0`, and `1 < 5-1` – Matt Jan 17 '16 at 01:47
  • @user3886450 Wouldn't removing the subsequence `{7,8,2}` produce a lower average? (I hope you'll pardon me if the answer should've been obvious.) – Ouroborus Jan 17 '16 at 01:51
  • 2
    @Matt As near as I can tell, the array you're trying to find a minimum average for is actually `arr[0..i-1,j+1..n-1]` – Ouroborus Jan 17 '16 at 01:53
  • @Ouroborus: That wouldn't work `{5,1}` has average 3. And you can't remove 2(its index == n-1). @Matt: The elements you remove are not continuous. – user3813674 Jan 17 '16 at 01:56
  • @user3886450 Ah, of course, I see it now. – Ouroborus Jan 17 '16 at 01:58

1 Answers1

0

Let's find the average value using binary search.

Suppose, that sum of all elements is S.

For given x let's check if exist i and j such that avg of all elements except from i to j less or equal to x.

To do that, let's subtract x from all elements in arr. We need to check if exists i and j such that sum of all elements except from i to j less or equal to zero. To do that, lets find sum of all elements in current array: S' = S - x * n. So we want to find i and j such that sum from i to j will be greater or equal than S'. To do that, let's find subarray with the larges sum. And this can be done using elegant Jay Kadane's algorithm: https://en.wikipedia.org/wiki/Maximum_subarray_problem

When to terminate binary search? When the maximum subarray sum will be zero (or close enough).

Time complexity: O(n log w), w - presicion of the binary search.

SashaMN
  • 658
  • 4
  • 15