Find the last remaining element after repeated removal of odd and even indexed elements alternately | Java program for the above approach ; Function to calculate the last remaining element from the sequence ; If dp [ n ] is already calculated ; Base Case : ; Recursive call ; Return the value of dp [ n ] ; Driver Code ; Given N ; Stores the ; Function call
import java . util . * ; class GFG { static int lastRemaining ( int n , HashMap < Integer , Integer > dp ) { if ( dp . containsKey ( n ) ) return dp . get ( n ) ; if ( n == 1 ) return 1 ; else dp . put ( n , 2 * ( 1 + n / 2 - lastRemaining ( n / 2 , dp ) ) ) ; return dp . get ( n ) ; } public static void main ( String [ ] args ) { int N = 5 ; HashMap < Integer , Integer > dp = new HashMap < Integer , Integer > ( ) ; System . out . print ( lastRemaining ( N , dp ) ) ; } }