Maximum subsequence sum such that no three are consecutive in O ( 1 ) space | Function to calculate the maximum subsequence sum such that no three elements are consecutive ; when N is 1 , answer would be the only element present ; when N is 2 , answer would be sum of elements ; variable to store sum up to i - 3 ; variable to store sum up to i - 2 ; variable to store sum up to i - 1 ; variable to store the final sum of the subsequence ; find the maximum subsequence sum up to index i ; update first , second and third ; return ans ; ; Driver code ; Input ; Function call
def maxSumWO3Consec ( A , N ) : NEW_LINE INDENT if ( N == 1 ) : NEW_LINE INDENT return A [ 0 ] NEW_LINE DEDENT if ( N == 2 ) : NEW_LINE INDENT return A [ 0 ] + A [ 1 ] NEW_LINE DEDENT third = A [ 0 ] NEW_LINE second = third + A [ 1 ] NEW_LINE first = max ( second , A [ 1 ] + A [ 2 ] ) NEW_LINE sum = max ( max ( third , second ) , first ) NEW_LINE for i in range ( 3 , N , 1 ) : NEW_LINE INDENT sum = max ( max ( first , second + A [ i ] ) , third + A [ i ] + A [ i - 1 ] ) NEW_LINE third = second NEW_LINE second = first NEW_LINE first = sum NEW_LINE DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT A = [ 3000 , 2000 , 1000 , 3 , 10 ] NEW_LINE N = len ( A ) NEW_LINE print ( maxSumWO3Consec ( A , N ) ) NEW_LINE DEDENT