Minimum number of given operations required to reduce a number to 2 | Java program for the above approach ; Function to find the minimum number of operations required to reduce n to 2 ; Initialize a dp array ; Handle the base case ; Iterate in the range [ 2 , n ] ; Check if i * 5 <= n ; Check if i + 3 <= n ; Return the result ; Driver code ; Given Input ; Function Call ; Print the result
public class GFG { static int findMinOperations ( int n ) { int i = 0 ; int dp [ ] = new int [ n + 1 ] ; for ( i = 0 ; i < n + 1 ; i ++ ) { dp [ i ] = 999999 ; } dp [ 2 ] = 0 ; for ( i = 2 ; i < n + 1 ; i ++ ) { if ( i * 5 <= n ) { dp [ i * 5 ] = Math . min ( dp [ i * 5 ] , dp [ i ] + 1 ) ; } if ( i + 3 <= n ) { dp [ i + 3 ] = Math . min ( dp [ i + 3 ] , dp [ i ] + 1 ) ; } } return dp [ n ] ; } public static void main ( String [ ] args ) { int n = 28 ; int m = findMinOperations ( n ) ; if ( m != 9999 ) System . out . println ( m ) ; else System . out . println ( - 1 ) ; } }