Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the maximum value in an array that's the sum of 3 other values

Given a very large integer array, I need to find the maximum value of a4, such that:

a4 = a1 + a2 + a3

Where the ai's are all values in the array.

How would I do this?

Note: Using 4 for loops is not the ideal solution.

like image 513
53by97 Avatar asked Apr 22 '14 05:04

53by97


People also ask

How do you find the maximum 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 the largest three numbers in an array?

Solution Approach For the largest three elements, we will create three elements holding their values, max, max2 and max3 and set these values to arr[0]. if (arr[i] > max) -> max3 = max2, max2 = max , max = arr[i]. else if (arr[i] > max2) -> max3 = max2, max2 = arr[i]. else if (arr[i] > max3) -> max3 = arr[i].

How do you find the maximum number of elements in two arrays?

Use a hash to pick unique n maximum elements of both arrays, giving priority to A[]. Initialize result array as empty. Traverse through A[], copy those elements of A[] that are present in the hash. This is done to keep the order of elements the same.


1 Answers

There is a simple (expected) O(n^2) solution:

  1. Iterate through all pairs of array elements (a, b) and store their sum in a hash table.
  2. Iterate through all candidate pairs (a4, a1) and check whether a4 - a1 is in the table. The maximum over all valid a4 is the solution. Of course you should process a4 from largest to smallest, but that doesn't affect the asymptotics.

If you want to avoid using an element more than once, you need some additional information stored in the hash table so that you can filter out pairs that colide with a1 or a4 fast.

If the integers in the array are bounded (max - min <= C), it might be useful to know that you can achieve O(n + C log C) using a discrete fourier transform (solvable using FFT).

like image 139
Niklas B. Avatar answered Oct 18 '22 22:10

Niklas B.