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 ; ; Input ; Function call
function maxSumWO3Consec ( A , N ) { if ( N == 1 ) return A [ 0 ] ; if ( N == 2 ) return A [ 0 ] + A [ 1 ] ; let third = A [ 0 ] ; let second = third + A [ 1 ] ; let first = Math . max ( second , A [ 1 ] + A [ 2 ] ) ; let sum = Math . max ( Math . max ( third , second ) , first ) ; for ( let i = 3 ; i < N ; i ++ ) { sum = Math . max ( Math . max ( first , second + A [ i ] ) , third + A [ i ] + A [ i - 1 ] ) ; third = second ; second = first ; first = sum ; } return sum ; } let A = [ 3000 , 2000 , 1000 , 3 , 10 ] ; let N = A . length ; document . write ( maxSumWO3Consec ( A , N ) ) ;