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 program to test above function ; Function calling
#include <bits/stdc++.h> NEW_LINE using namespace std ; 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 ; } int main ( ) { int arr [ ] = { 80 , 2 , 6 , 3 , 100 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Maximum ▁ difference ▁ is ▁ " << maxDiff ( arr , n ) ; return 0 ; }