Maximum difference between two elements

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)

C++:
01 int maxProfit(int A[], int size)
02 {
03     int min=A[0];
04     int maxgap=A[1]A[0];
05     for(int i=1;i<size;i++){
06         if(A[i]<min)
07             min=A[i];
08         if(A[i]min>maxgap)
09             maxgap=A[i]min;
10     }
11     return maxgap;
12 }
Advertisements
This entry was posted in Array and linked list. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s