Search code examples
algorithmdivide-and-conquer

Implement simple algorithm using divide and conquer


I am trying to implement the following algorithm using the divide and conquer method in order to get the running time to O(n*logn).

Given a sequence of numbers a_1, a_2,…, a_n and a number k, find i and j such that 1<= j – i <= k while maximizing a_i + a_j.

For example for the sequence 10,2,0,8,1,7,1,0,11 and k = 2, the maximum value is 15 = 8 + 7.

I have implemented some sort of divide and conquer method, but I'm struggling to figure out how to check values that go across each of the divide intervals. Here is what I have so far:

int MaxInterval(int array[], int left, int right, int k)
{
    int BestSum = 0;
    int sumL = 0;
    int sum = 0;
    int sumR = 0;
    int sumMid = 0;
    int count = 0;
    if( right - left <= 2*k-3 ) //
    {
      //elaborate straightforward search right way
      for(int i = left; i <= right; i++)
      {
          sum = 0;
          count = k;
          for(int j = i+1; j <= right; j++ )
          {
              if(count == 0) break;
              sum = array[i] + array [j];
              if(sum > BestSum) BestSum = sum;
              count--;
          }

      }
      return BestSum;
    }
    int mid = (right + left)/2;
    sumL = MaxInterval(array, left, mid, k);
    sumR = MaxInterval(array, mid + 1, right, k);
    sumMid = MaxInterval(array, max(left, mid - k + 2), min(right, mid + k - 1), k);
    return max(max(sumL, sumR), sumMid);
}

I think I am on some-what of the right track, I'm just struggling to figure out how to incorporate check sums of numbers that go across two of the intervals, without using a brute-force method which would yield O(n^2) complexity.

If there are any pointers or tips on how I can continue this, it would be greatly appreciated. Also, I am currently working under the assumption that there is an even number of integers in the array. Thanks guys.


Solution

  • Some clues in pseudocode. Example for n=8, k = 2 - this code will search the best result from a[0..3], a[4..7] and a[2..5]. Notice that I've removed additional arrays.

    int MaxInterval(int array[], int left, int right, int k)
    {
        if( right - left <= 2*k-1 ) //
        {
          //elaborate straightforward search right way
          return BestSum;
        }
        sumL = MaxInterval(array, left, mid, k);
        sumR = MaxInterval(array, mid + 1, right, k);
        sumMid = MaxInterval(array, max(left, mid - k + 1), min(right, mid + k), k);
        return max(sumL, sumR, sumMid);
    }