Cost of creating smallest subsequence with sum of difference between adjacent elements maximum |  ; initializing cost = 0 ; to store the removed element ; this will store the sum of the subsequence ; checking all the element of the vector ; storing the value of arr [ i ] in temp variable ; if the situation like arr [ i - 1 ] < arr [ i ] < arr [ i + 1 ] or arr [ i - 1 ] > arr [ i ] > arr [ i + 1 ] occur remove arr [ i ] i . e , temp from sequence ; insert the element in the set removedElements ; storing the value of arr [ i ] in temp ; taking the element not in removedElements ; adding the value of elements of subsequence ; if we have to remove the element then we need to add the cost associated with the element ; printing the sum of the subsequence with minimum length possible ; printing the cost incurred in creating subsequence ; Driver code ; calling the function
function costOfSubsequence ( N , arr , costArray ) { let i , temp ; let cost = 0 ; let removedElements = new Set ( ) ; let ans = 0 ; for ( i = 1 ; i < ( N - 1 ) ; i ++ ) { temp = arr [ i ] ; if ( ( ( arr [ i - 1 ] < temp ) && ( temp < arr [ i + 1 ] ) ) || ( ( arr [ i - 1 ] > temp ) && ( temp > arr [ i + 1 ] ) ) ) { removedElements . add ( temp ) ; } } for ( i = 0 ; i < ( N ) ; i ++ ) { temp = arr [ i ] ; if ( ! removedElements . has ( temp ) ) { ans += arr [ i ] ; } else { cost += costArray [ i ] ; } } document . write ( ans + " " ) ; document . write ( cost ) ; } let N ; N = 4 ; let arr = [ 1 , 3 , 4 , 2 ] ; let costArray = [ 0 , 1 , 0 , 0 ] ; costOfSubsequence ( N , arr , costArray ) ;