Find the last remaining element after repeated removal of odd and even indexed elements alternately | 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 ] ; Given N ; Stores the ; Function call
function lastRemaining ( n , dp ) { if ( dp . hasOwnProperty ( n ) ) return dp [ n ] ; if ( n === 1 ) return 1 ; else dp [ n ] = 2 * ( 1 + parseInt ( n / 2 ) - lastRemaining ( parseInt ( n / 2 ) , dp ) ) ; return dp [ n ] ; } var N = 5 ; var dp = { } ; document . write ( lastRemaining ( N , dp ) ) ;