text: Minimize cost to reach end of an array by two forward jumps or one backward jump in each move | C # Program to implement the above approach ; Function to find the minimum cost to reach the end of an array ; Base Case : When N < 3 ; Store the results in table ; Initialize base cases ; Iterate over the range [ 2 , N - 2 ] to construct the dp array ; Handle case for the last index , i . e . N - 1 ; Print the answer ; Driver Code
code: using System ; public class GFG { static void minCost ( int [ ] arr , int n ) { if ( n < 3 ) { Console . WriteLine ( arr [ 0 ] ) ; return ; } int [ ] dp = new int [ n ] ; dp [ 0 ] = arr [ 0 ] ; dp [ 1 ] = dp [ 0 ] + arr [ 1 ] + arr [ 2 ] ; for ( int i = 2 ; i < n - 1 ; i ++ ) dp [ i ] = Math . Min ( dp [ i - 2 ] + arr [ i ] , dp [ i - 1 ] + arr [ i ] + arr [ i + 1 ] ) ; dp [ n - 1 ] = Math . Min ( dp [ n - 2 ] , dp [ n - 3 ] + arr [ n - 1 ] ) ; Console . WriteLine ( dp [ n - 1 ] ) ; } public static void Main ( string [ ] args ) { int [ ] arr = { 9 , 4 , 6 , 8 , 5 } ; int N = arr . Length ; minCost ( arr , N ) ; } }