**Problem statement**

Maximum difference between two elements such that larger element appears after the smaller number

**Explanation:**

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

**Examples:**

- If array is [2, 3, 10, 6, 4, 8, 1] then returned value should be 8 (Diff between 10 and 2).
- If array is [ 7, 9, 5, 6, 3, 2 ] then returned value should be 2 (Diff between 7 and 9)

**Conclusion:**

You have to take first number of array and check it with remaining array elements.

Then find the largest number in remaining array (excluding number at array index 0).

Then find the difference between largest number from remaining array and first number from array.

This will be the largest difference between two elements.

### C program to find maximum difference between two elements such that larger element appears after the smaller number

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#include<stdio.h> int main() { int arr[100],i=0,j=0,diff=0,n=0; printf("Enter array size\n"); scanf("%d",&n); printf("Enter elements of array\n"); for(i=0;i<n;i++) { scanf("%d",&arr[i]); } i=0; diff= arr[i+1]-arr[i]; for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { if(diff<(arr[j]-arr[i])) { diff=arr[j]-arr[i]; } } } printf("The maximum difference is %d",diff); } |

**Output:**

1 2 3 4 5 |
Enter array size 6 Enter elements of array 7 9 5 6 3 2 The maximum difference is 2 |