Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find largest pair sum in array of integers

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.

like image 220
Mitsos101 Avatar asked Mar 09 '16 17:03

Mitsos101


People also ask

How do you find the highest sum of an array?

Find the Maximum subarray sum using Kadane' Algorithm. Keep that subarray intact and multiply the rest with -1. Considering the sum of the whole array as S, and the largest sum contiguous subarray as S1, the total sum will be equal to -(S-S1) + S1 = 2*S1 – S. This is the required sum.

How do you find two largest numbers in an array?

Take two variables and initiliaze them with zero. Iterate through each element of the array and compare each number against these two number. If current number is greater than maxOne then maxOne = number and maxTwo = maxOne. Otherwise if it only greater than maxTwo then we only update maxTwo with current number.

How do you find pairs in an array whose sum is equal to some number?

Follow the steps below to solve the given problem: Initialize the count variable with 0 which stores the result. Iterate arr and if the sum of ith and jth [i + 1…..n – 1] element is equal to sum i.e. arr[i] + arr[j] == sum, then increment the count variable. Return the count.


2 Answers

It's quite simple to do in O (n), not O (n²) like your solution.

For each j, 0 ≤ j < n, 
calculate m [j] = "largest element from a [j] to a [n - 1]. ". 
Obviously m [n - 1] = a [n - 1], m [j] = max (a [j], m [j + 1]). 

Then for each i, 0 ≤ i < n - k, calculate a [i] + m [i + k], 
and pick the largest of these. 

It should be obvious how to do this without actually storing the values m [j] except for one.

like image 181
gnasher729 Avatar answered Sep 23 '22 14:09

gnasher729


//assuming we checked first for n<=k
int max_lagged = arr_sums[0];
int max_sum = max_lagged+arr_sums[k];
int sum;
for (int i = k+1 ; i < n; i++) {
    if (arr_sums[i-k] > max_lagged) {
        max_lagged=arr_sums[i-k];
    }
    sum = arr_sums[i] + max_lagged;
    if ( sum > max_sum ) {
        max_sum = sum;
    }
}
like image 26
Matt Timmermans Avatar answered Sep 25 '22 14:09

Matt Timmermans