Maximum difference between two elements

Source: Internet
Author: User
Maximum difference between two elementsfrom http://www.geeksforgeeks.org/maximum-difference-between-two-elements/April 10,201 0

Given an array arr [] of integers, find out the difference between any two elementsSuch that larger element appears after the smaller numbeR in arr [].

Examples: If array is [2, 3, 10, 6, 4, 8, 1] then returned value shoshould be 8 (diff between 10 and 2 ). if array is [7, 9, 5, 6, 3, 2] then returned value shoshould be 2 (diff between 7 and 9)

Method 1 (simple)
Use two loops. in the outer loop, pick elements one by one and in the inner loop calculate the difference of the picked element with every other element in the array and compare the difference with the maximum difference calculated so far.

# Include <stdio. h> /* The function assumes that there are at least two Elements in array. The function returns a negative value if the array is Sorted in decreasing order. Returns 0 if elements are equal */ Int Maxdiff ( Int Arr [], Int Arr_size) { Int Max_diff = arr [1]-Arr [0]; Int I, J; For (I = 0; I <arr_size; I ++) { For (J = I + 1; j <arr_size; j ++) { If (ARR [J]-Arr [I]> max_diff) Max_diff = arr [J]-Arr [I]; } } Return Max_diff; } /* Driver program to test above function */ Int Main () { Int Arr [] = {1, 2, 90, 10,110 }; Printf ( "Maximum difference is % d" , Maxdiff (ARR, 5 )); Getchar (); Return 0; }

Time Complexity: O (N ^ 2)
Auxiliary space: O (1)

Method 2 (tricky and efficient)
In this method, instead of taking difference of the picked element with every other element, we take the difference with the minimum element found so far. So we need to keep track of 2 things:
1) maximum difference found so far (max_diff ).
2) minimum number visited so far (min_element ).

# Include <stdio. h> /* The function assumes that there are at least two Elements in array. The function returns a negative value if the array is Sorted in decreasing order. Returns 0 if elements are equal */ Int Maxdiff ( Int Arr [], Int Arr_size) { Int Max_diff = arr [1]-Arr [0]; Int Min_element = arr [0]; Int I; For (I = 1; I <arr_size; I ++) { If (ARR [I]-min_element> max_diff) Max_diff = arr [I]-min_element; If (ARR [I] <min_element) Min_element = arr [I]; } Return Max_diff; } /* Driver program to test above function */ Int Main () { Int Arr [] = {1, 2, 6, 80,100 }; Int Size = Sizeof (ARR )/ Sizeof (ARR [0]); Printf ( "Maximum difference is % d" , Maxdiff (ARR, size )); Getchar (); Return 0; }

Time Complexity: O (N)
Auxiliary space: O (1)

Method 3 (another tricky solution)
First find the difference between the adjacent elements of the array and store all differences in an auxiliary array diff [] of size n-1. now this problems turns into finding the maximum sum subarray of this difference array.
Thanks to shubham Mittal for suggesting this solution.

# Include <stdio. h> Int Maxdiff ( Int Arr [], Int N) { // Create a diff array of size n-1. The array will hold // The difference of Adjacent Elements Int Diff [n-1]; For ( Int I = 0; I <n-1; I ++) Diff [I] = arr [I + 1]-Arr [I]; // Now find the maximum sum subarray in diff Array Int Max_diff = diff [0]; For ( Int I = 1; I <n-1; I ++) { If (Diff [I-1]> 0) Diff [I] + = diff [I-1]; If (Max_diff <diff [I]) Max_diff = diff [I]; } Return Max_diff; } /* Driver program to test above function */ Int Main () { Int Arr [] = {80, 2, 6, 3,100 }; Int Size = Sizeof (ARR )/ Sizeof (ARR [0]); Printf ( "Maximum difference is % d" , Maxdiff (ARR, size )); Return 0; }

Output:

 
98

This method is also O (n) time complexity solution, but it requires O (n) extra space

Time Complexity: O (N)
Auxiliary space: O (N)

We can modify the above method to work in O (1) extra space. instead of creating an auxiliary array, we can calculate diff and Max sum in same loop. following is the space optimized version.

Int Maxdiff ( Int Arr [], Int N) { // Initialize diff, current sum and Max sum Int Diff = arr [1]-Arr [0]; Int Curr_sum = diff; Int Max_sum = curr_sum; For ( Int I = 1; I <n-1; I ++) { // Calculate current diff Diff = arr [I + 1]-Arr [I]; // Calculate current sum If (Curr_sum> 0) Curr_sum + = diff; Else Curr_sum = diff; // Update Max sum, if needed If (Curr_sum> max_sum) Max_sum = curr_sum; } Return Max_sum; }

Time Complexity: O (N)
Auxiliary space: O (1)

Please write comments if you find any bug in above codes/algorithms, or find other ways to solve the same problem

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.