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
dp = [ ] NEW_LINE def maxSum ( i , subarr ) : NEW_LINE INDENT if ( i >= len ( subarr ) ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT if ( dp [ i ] != - 1 ) : NEW_LINE INDENT return dp [ i ] NEW_LINE DEDENT dp [ i ] = max ( maxSum ( i + 1 , subarr ) , subarr [ i ] + maxSum ( i + 2 , subarr ) ) NEW_LINE return dp [ i ] NEW_LINE DEDENT def Func ( arr ) : NEW_LINE INDENT subarr = arr NEW_LINE subarr . pop ( ) NEW_LINE global dp NEW_LINE dp = [ - 1 ] * ( len ( subarr ) ) NEW_LINE max1 = maxSum ( 0 , subarr ) NEW_LINE subarr = arr NEW_LINE subarr = subarr [ : ] NEW_LINE del dp NEW_LINE dp = [ - 1 ] * ( len ( subarr ) ) NEW_LINE max2 = maxSum ( 0 , subarr ) NEW_LINE print ( max ( max1 , max2 ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 1 ] NEW_LINE Func ( arr ) NEW_LINE DEDENT