I have a working solution for my problem but now I want to improve it.
Consider the array
3,4,5,9,1,2,8
I need to find the max difference between two elements at position i
and j
such that i < j
that is I want to find max difference between two elements where the 2nd element comes after 1st element.
In the input I gave the answer is 7
because 8-1 = 7
and 8
is after 1
.
The program works but when I have a very large array it takes lot of time. Can we improve on it?
function fMax($arr)
{
$sum = $arr[1] - $arr[0];
for($i=0;$i<count($arr);$i++)
{
for($j=$i+1;$j<count($arr);$j++)
{
if($sum < $arr[$j] - $arr[$i])
{
$sum = $arr[$j] - $arr[$i];
}
}
}
return $sum;
}
Thanks a lot to all the answers. I have used the code by codeaddict and it works fast.
Given an array of integers and a number k, find the maximum sum of a subarray of size k. Examples: Input : arr[] = {100, 200, 300, 400} k = 2 Output : 700 Input : arr[] = {1, 4, 2, 10, 23, 3, 1, 0, 20} k = 4 Output : 39 We get maximum sum by adding subarray {4, 2, 10, 23} of size 4.
The maximum pair sum is the largest pair sum in a list of pairs. For example, if we have pairs (1,5) , (2,3) , and (4,4) , the maximum pair sum would be max(1+5, 2+3, 4+4) = max(6, 5, 8) = 8 .
The above syntax of max() function allows us to find the sum of list in list using the key=sum. max(list1, key=sum), this finds the list with maximum sum of elements and then sum(max(list1, key=sum)) returns us the sum of that list.
Your current approach is O(N^2)
you can improve it to O(N)
.
You are comparing each element with every other element. Instead you can keep track of the max difference and min element seen so far.
So every time you test a new element you see
PHP function:
function ImprovedFindMax($arr) {
// initial max sum.
$sum = $arr[1] - $arr[0];
// initial min.
$min = $arr[0];
// iterate for every other ele starting from 2nd.
for($i=1;$i<count($arr);$i++) {
// if this ele give larger sum then update sum.
if($arr[$i] - $min > $sum) {
$sum = $arr[$i] - $min;
}
// if this ele is smaller than min..update min.
if($arr[$i] < $min) {
$min = $arr[$i];
}
}
// return $sum which will be the max sum.
return $sum;
}
Ideone Link
One iteration, track the minimum and the maxdiff. At each element, if the value is less than the minimum, set the minimum to the value; else, if the value - minimum is greater than maxdiff, set the maxdiff to that difference. Turns it from an O(n^2) to O(n).
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