Find the last remaining element after repeated removal of odd and even indexed elements alternately | C # 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
using System ; using System . Collections . Generic ; class GFG { static int lastRemaining ( int n , Dictionary < int , int > dp ) { if ( dp . ContainsKey ( n ) ) return dp [ n ] ; if ( n == 1 ) return 1 ; else dp . Add ( n , 2 * ( 1 + n / 2 - lastRemaining ( n / 2 , dp ) ) ) ; return dp [ n ] ; } public static void Main ( String [ ] args ) { int N = 5 ; Dictionary < int , int > dp = new Dictionary < int , int > ( ) ; Console . Write ( lastRemaining ( N , dp ) ) ; } }