Sum of minimum difference between consecutive elements of an array | C ++ program for finding the minimum sum of difference between consecutive elements ; function to find minimum sum of difference of consecutive element ; ul to store upper limit ll to store lower limit ; storethe lower range in ll and upper range in ul ; initialize the answer with 0 ; iterate for all ranges ; case 1 , in this case the difference will be 0 ; change upper limit and lower limit ; case 2 ; store the difference ; case 3 ; store the difference ; Driver code ; array of range
#include <bits/stdc++.h> NEW_LINE using namespace std ; int solve ( pair < int , int > v [ ] , int n ) { int ans , ul , ll ; ll = v [ 0 ] . first ; ul = v [ 0 ] . second ; ans = 0 ; for ( int i = 1 ; i < n ; i ++ ) { if ( ( v [ i ] . first <= ul && v [ i ] . first >= ll ) || ( v [ i ] . second >= ll && v [ i ] . second <= ul ) ) { if ( v [ i ] . first > ll ) { ll = v [ i ] . first ; } if ( v [ i ] . second < ul ) { ul = v [ i ] . second ; } } else if ( v [ i ] . first > ul ) { ans += abs ( ul - v [ i ] . first ) ; ul = v [ i ] . first ; ll = v [ i ] . first ; } else if ( v [ i ] . second < ll ) { ans += abs ( ll - v [ i ] . second ) ; ul = v [ i ] . second ; ll = v [ i ] . second ; } } return ans ; } int main ( ) { pair < int , int > v [ ] = { { 1 , 3 } , { 2 , 5 } , { 6 , 8 } , { 1 , 2 } , { 2 , 3 } } ; int n = sizeof ( v ) / sizeof ( v [ 0 ] ) ; cout << solve ( v , n ) << endl ; return 0 ; }