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
< ? php function maxSum ( $ grid , $ n ) { $ incl = max ( $ grid [ 0 ] [ 0 ] , $ grid [ 1 ] [ 0 ] ) ; $ excl = 0 ; $ excl_new ; for ( $ i = 1 ; $ i < $ n ; $ i ++ ) { $ excl_new = max ( $ excl , $ incl ) ; $ incl = $ excl + max ( $ grid [ 0 ] [ $ i ] , $ grid [ 1 ] [ $ i ] ) ; $ excl = $ excl_new ; } return max ( $ excl , $ incl ) ; } $ grid = array ( array ( 1 , 2 , 3 , 4 , 5 ) , array ( 6 , 7 , 8 , 9 , 10 ) ) ; $ n = 5 ; echo maxSum ( $ grid , $ n ) ; ? >