Maximum difference between two elements such that larger element appears after the smaller number | C # program to find Maximum difference between two elements such that larger element appears after the smaller number ; The function assumes that there are at least two elements in array . The function returns a negative value if the array is sorted in decreasing order and returns 0 if elements are equal ; Initialize diff , current sum and max sum ; Calculate current diff ; Calculate current sum ; Update max sum , if needed ; Driver Code ; Function calling
using System ; class GFG { static int maxDiff ( int [ ] arr , int n ) { int diff = arr [ 1 ] - arr [ 0 ] ; int curr_sum = diff ; int max_sum = curr_sum ; for ( int i = 1 ; i < n - 1 ; i ++ ) { diff = arr [ i + 1 ] - arr [ i ] ; if ( curr_sum > 0 ) curr_sum += diff ; else curr_sum = diff ; if ( curr_sum > max_sum ) max_sum = curr_sum ; } return max_sum ; } public static void Main ( ) { int [ ] arr = { 80 , 2 , 6 , 3 , 100 } ; int n = arr . Length ; Console . WriteLine ( " Maximum ▁ difference ▁ is ▁ " + maxDiff ( arr , n ) ) ; } }