Maximum sum in a 2 x n grid such that no two elements are adjacent | Function to find max sum without adjacent ; Sum including maximum element of first column ; Not including first column 's element ; Traverse for further elements ; Update max_sum on including or excluding of previous column ; Include current column . Add maximum element from both row of current column ; If current column doesn 't to be included ; Return maximum of excl and incl As that will be the maximum sum ; Driver code
def maxSum ( grid , n ) : NEW_LINE INDENT incl = max ( grid [ 0 ] [ 0 ] , grid [ 1 ] [ 0 ] ) NEW_LINE excl = 0 NEW_LINE for i in range ( 1 , n ) : NEW_LINE INDENT excl_new = max ( excl , incl ) NEW_LINE incl = excl + max ( grid [ 0 ] [ i ] , grid [ 1 ] [ i ] ) NEW_LINE excl = excl_new NEW_LINE DEDENT return max ( excl , incl ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT grid = [ [ 1 , 2 , 3 , 4 , 5 ] , [ 6 , 7 , 8 , 9 , 10 ] ] NEW_LINE n = 5 NEW_LINE print ( maxSum ( grid , n ) ) NEW_LINE DEDENT // This code is contributed by Ryuga NEW_LINE