Maximum sum in circular array such that no two elements are adjacent | Function to calculate the sum from 0 th position to ( n - 2 ) th position ; copy the element of original array to dp [ ] ; find the maximum element in the array ; start from 2 nd to n - 1 th pos ; traverse for all pairs bottom - up approach ; dp - condition ; find maximum sum ; return the maximum ; Function to find the maximum sum from 1 st position to n - 1 - th position ; Traverse from third to n - th pos ; bootom - up approach ; dp condition ; find max sum ; return max ; Driver Code
def maxSum1 ( arr , n ) : NEW_LINE INDENT dp = [ 0 ] * n NEW_LINE maxi = 0 NEW_LINE for i in range ( n - 1 ) : NEW_LINE INDENT dp [ i ] = arr [ i ] NEW_LINE if ( maxi < arr [ i ] ) : NEW_LINE INDENT maxi = arr [ i ] NEW_LINE DEDENT DEDENT for i in range ( 2 , n - 1 ) : NEW_LINE INDENT for j in range ( i - 1 ) : NEW_LINE INDENT if ( dp [ i ] < dp [ j ] + arr [ i ] ) : NEW_LINE INDENT dp [ i ] = dp [ j ] + arr [ i ] NEW_LINE if ( maxi < dp [ i ] ) : NEW_LINE INDENT maxi = dp [ i ] NEW_LINE DEDENT DEDENT DEDENT DEDENT return maxi NEW_LINE DEDENT def maxSum2 ( arr , n ) : NEW_LINE INDENT dp = [ 0 ] * n NEW_LINE maxi = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT dp [ i ] = arr [ i ] NEW_LINE if ( maxi < arr [ i ] ) : NEW_LINE INDENT maxi = arr [ i ] NEW_LINE DEDENT DEDENT for i in range ( 3 , n ) : NEW_LINE INDENT for j in range ( 1 , i - 1 ) : NEW_LINE INDENT if ( dp [ i ] < arr [ i ] + dp [ j ] ) : NEW_LINE INDENT dp [ i ] = arr [ i ] + dp [ j ] NEW_LINE if ( maxi < dp [ i ] ) : NEW_LINE INDENT maxi = dp [ i ] NEW_LINE DEDENT DEDENT DEDENT DEDENT return maxi NEW_LINE DEDENT def findMaxSum ( arr , n ) : NEW_LINE INDENT return max ( maxSum1 ( arr , n ) , maxSum2 ( arr , n ) ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findMaxSum ( arr , n ) ) NEW_LINE DEDENT