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
using System ; class GFG { static int solve ( int [ , ] v , int n ) { int ans , ul , ll ; int first = 0 ; int second = 1 ; 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 += Math . Abs ( ul - v [ i , first ] ) ; ul = v [ i , first ] ; ll = v [ i , first ] ; } else if ( v [ i , second ] < ll ) { ans += Math . Abs ( ll - v [ i , second ] ) ; ul = v [ i , second ] ; ll = v [ i , second ] ; } } return ans ; } static void Main ( ) { int [ , ] v = new int [ 5 , 2 ] { { 1 , 3 } , { 2 , 5 } , { 6 , 8 } , { 1 , 2 } , { 2 , 3 } } ; int n = 5 ; Console . WriteLine ( solve ( v , n ) ) ; } }