Minimize cost to reach end of an array by two forward jumps or one backward jump in each move | Java 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
import java . io . * ; import java . util . * ; class GFG { static void minCost ( int arr [ ] , int n ) { if ( n < 3 ) { System . out . println ( 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 ] ) ; System . out . println ( dp [ n - 1 ] ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 9 , 4 , 6 , 8 , 5 } ; int N = arr . length ; minCost ( arr , N ) ; } }