Maximum sum in circular array such that no two elements are adjacent | Set 2 | Store the maximum possible at each index ; When i exceeds the index of the last element simply return 0 ; If the value has already been calculated , directly return it from the dp array ; The next states are don 't take  this element and go to (i + 1)th state  else take this element  and go to (i + 2)th state ; function to find the max value ; subarr contains elements from 0 to arr . size ( ) - 2 ; Initializing all the values with - 1 ; Calculating maximum possible sum for first case ; subarr contains elements from 1 to arr . size ( ) - 1 ; Re - initializing all values with - 1 ; Calculating maximum possible sum for second case ; Printing the maximum between them ; Driver code
let dp = [ ] ; function maxSum ( i , subarr ) { if ( i >= subarr . length ) return 0 ; if ( dp [ i ] != - 1 ) return dp [ i ] ; dp [ i ] = Math . max ( maxSum ( i + 1 , subarr ) , subarr [ i ] + maxSum ( i + 2 , subarr ) ) ; return dp [ i ] ; } function Func ( arr ) { let subarr = arr ; subarr . pop ( ) ; dp = new Array ( subarr . length ) ; for ( let i = 0 ; i < subarr . length ; i ++ ) { dp [ i ] = - 1 ; } let max1 = maxSum ( 0 , subarr ) ; subarr = arr ; subarr . shift ( ) ; dp = [ ] ; dp = new Array ( subarr . length ) ; for ( let i = 0 ; i < dp . length ; i ++ ) { dp [ i ] = - 1 ; } let max2 = maxSum ( 0 , subarr ) ; document . write ( Math . max ( max1 , max2 ) + " " ) ; } let arr = [ 1 , 2 , 3 , 1 ] ; Func ( arr ) ;