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
import java . util . * ; class GFG { public static void costOfSubsequence ( int N , int [ ] arr , int [ ] costArray ) { int i , temp ; int cost = 0 ; Set < Integer > removedElements = new HashSet < Integer > ( ) ; int 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 . contains ( temp ) ) ) { ans += arr [ i ] ; } else { cost += costArray [ i ] ; } } System . out . print ( ans + " , ▁ " ) ; System . out . print ( cost ) ; } public static void main ( String [ ] args ) { int N ; N = 4 ; int [ ] arr = { 1 , 3 , 4 , 2 } ; int [ ] costArray = { 0 , 1 , 0 , 0 } ; costOfSubsequence ( N , arr , costArray ) ; } }