c - Maximum difference between two elements -
given array of integers, have find out maximum difference between 2 elements such larger number appearing after smaller number in array.i used simple approach , took difference minimum number encountered far keeping track of 2 things
1.maximum difference
2.minimum number visited far.
int min_element=arr[0]; int diff=arr[1]-arr[0]; for(i=1;i<n;i++) { if(arr[i]-min_element>diff) diff=arr[i]-min_element; if(arr[i]<min_element) min_element=arr[i]; } return diff;
is there better approach solving problem?
as stands, algorithm optimal, constant factor.
reading array of n
integers takes Ω(n)
. algorithm o(n)
, you're good.
Comments
Post a Comment