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.
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.
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].
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.
There is a simple (expected) O(n^2) solution:
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With