Maximum sum in circular array such that no two elements are adjacent | Set 2 | Java program to find maximum sum in circular array such that no two elements are adjacent ; 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
import java . util . * ; class GFG { static Vector < Integer > dp = new Vector < > ( ) ; static int maxSum ( int i , Vector < Integer > subarr ) { if ( i >= subarr . size ( ) ) return 0 ; if ( dp . get ( i ) != - 1 ) return dp . get ( i ) ; dp . add ( i , Math . max ( maxSum ( i + 1 , subarr ) , subarr . get ( i ) + maxSum ( i + 2 , subarr ) ) ) ; return dp . get ( i ) ; } static void Func ( Vector < Integer > arr ) { Vector < Integer > subarr = new Vector < > ( ) ; subarr . addAll ( arr ) ; subarr . remove ( subarr . size ( ) - 1 ) ; dp . setSize ( subarr . size ( ) ) ; Collections . fill ( dp , - 1 ) ; int max1 = maxSum ( 0 , subarr ) ; subarr = arr ; subarr . remove ( 0 ) ; dp . clear ( ) ; dp . setSize ( subarr . size ( ) ) ; Collections . fill ( dp , - 1 ) ; int max2 = maxSum ( 0 , subarr ) ; System . out . print ( Math . max ( max1 , max2 ) + "NEW_LINE"); } public static void main ( String [ ] args ) { Vector < Integer > arr = new Vector < > ( ) ; arr . add ( 1 ) ; arr . add ( 2 ) ; arr . add ( 3 ) ; arr . add ( 1 ) ; Func ( arr ) ; }