Find largest pair sum in array of integers

Viewed 2980

How can I find the largest pair sum in an array of positive integers of size n, but with the integers at least at a distance k? (For example, if the first element is a[i], then the second element should be a[i+k] (or more).)

I tried this:

int max_sum = 0;
int sum;
for (int i = 0 ; i < n; i++) {
    for( int j = i + k; j < n; j++) {
        sum = arr_sums[i] + arr_sums[j];
        if ( sum > max_sum ) {
            max_sum = sum;

        }
    }
}

but it's too slow for large arrays.

2 Answers
Related