Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Maximum difference between two elements such that larger element appears after the smaller number in C
We are given an array of integers of size N. The task is to find the maximum difference between two elements such that the larger element appears after the smaller number. That is, Arr[j] − Arr[i] is maximum such that j > i.
Input:
Arr[] = {2, 1, 3, 8, 3, 19, 21}
Output: The maximum difference is 20
Explanation: The maximum difference is between 21 and 1, and 21 appears after 1 in the array.
Syntax
int maxDifference(int arr[], int n);
Approach
The optimal approach uses a single traversal to track the minimum element seen so far and calculates the maximum difference at each step −
- Initialize the maximum difference with the first two elements
- Keep track of the minimum element encountered so far
- For each element, calculate the difference with the minimum element
- Update the maximum difference if a larger difference is found
- Update the minimum element if a smaller element is found
Example
#include <stdio.h>
int maxDifference(int arr[], int n) {
// Maximum difference found so far
int maxDiff = arr[1] - arr[0];
// Minimum number visited so far
int minElement = arr[0];
for (int i = 1; i < n; i++) {
// Calculate difference with minimum element
if (arr[i] - minElement > maxDiff)
maxDiff = arr[i] - minElement;
// Update minimum element if current is smaller
if (arr[i] < minElement)
minElement = arr[i];
}
return maxDiff;
}
int main() {
int arr[] = {2, 1, 3, 8, 3, 19, 21};
int n = 7;
printf("Array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("<br>");
int result = maxDifference(arr, n);
printf("Maximum difference: %d<br>", result);
return 0;
}
Array: 2 1 3 8 3 19 21 Maximum difference: 20
How It Works
The algorithm works by maintaining two variables:
- minElement: Tracks the smallest element seen so far
- maxDiff: Stores the maximum difference found
For the array [2, 1, 3, 8, 3, 19, 21]:
- Initially: maxDiff = 1−2 = −1, minElement = 2
- At index 1: minElement becomes 1
- At index 2: maxDiff = 3−1 = 2
- At index 3: maxDiff = 8−1 = 7
- At index 5: maxDiff = 19−1 = 18
- At index 6: maxDiff = 21−1 = 20
Key Points
- Time complexity: O(n) − single traversal of the array
- Space complexity: O(1) − only two variables used
- The algorithm handles negative differences correctly
- Works for arrays with duplicate elements
Conclusion
This single−pass algorithm efficiently finds the maximum difference between two elements where the larger element appears after the smaller one. It optimally tracks the minimum element and maximum difference in linear time.
