Join the social network of Tech Nerds, increase skill rank, get work, manage projects...

• # Efficient method to find maximum difference between two elements in C?

• 0
• 0
• 0
• 0
• 0
• 0
• 0
• 0
• 261
Comment on it
``````#include<stdio.h>

int maxDiff(int a[], int n)
{
int maxDiff = -1; // Initialize Result

int maxRight = a[n-1]; // Initialize max element from right side

for (int i = n-2; i >= 0; i--)
{
if (a[i] > maxRight)
maxRight = a[i];
else
{
int diff = maxRight - a[i];
if (diff > maxDiff)
{
maxDiff = diff;
}
}
}
return maxDiff;
}

int main()
{
int a[] = {20, 2, 90, 10, 110};
printf("Maximum difference is %d",  maxDiff(a, 5));
getchar();
return 0;
}``````

Output:

`Maximum difference is 108`

Explanation:

In above program following procedure is followed:

• The maximum element is assumed to be the last element from right side and is assigned to maxRight.
• The loop tries to find maximum element from right side, if found max element is assigned to variable maxRight.
• The difference is between max element from right and currently visited element in the array which is then compared to maxDiff if less then difference is assigned to maxDiff.
• An efficient method as time complexity is O(n) since only one loop is involved.

## 0 Comment(s)

OR
OR
Register

OR
Fill out the form below and instructions to reset your password will be emailed to you:

• Hire
• Post Projects

### Post Projects

• All at 0 Cost ....
• Post Tech Job
• Select Best Bidder
• Track the Project
• Approve Work and Pay safely
• Browse Nerds
• Work
• Find Projects Find Projects
• UI Design and UX
• Software Engineering
View more...
View less...
• Marketing
• General
• Manage
• Company Company

### Manage Company

• All at 0 Cost ....
• Manage Company and Employee Profiles
• Company wide Employee Productivity Reports
• Knowledge Sharing and Collaboration Tools
• Get Sales Lead and Bid for Tech Projects
• Send Invoices and Receive Payment Safely
• Learn
• Nerd Digest Nerd Digest
• UI Design and UX
• Software Engineering
View more...
View less...
• Marketing
• General
• Tech Q & A Tech Q & A
• UI Design and UX
• Software Engineering
View more...
View less...
• Marketing
• General