Find the Maximum Alternate Subsequence Sum from a given array | Function to find maximum alternating subsequence sum ; Initialize sum to 0 ; Calculate the sum ; Return the final result ; Array initialization ; Length of array
function maxAlternatingSum ( arr , n ) { var max_sum = 0 ; var i = 0 ; while ( i < n ) { var current_max = arr [ i ] ; var k = i ; while ( k < n && ( ( arr [ i ] > 0 && arr [ k ] > 0 ) || ( arr [ i ] < 0 && arr [ k ] < 0 ) ) ) { current_max = Math . max ( current_max , arr [ k ] ) ; k += 1 ; } max_sum += current_max ; i = k ; } return max_sum ; } var arr = [ 1 , 2 , 3 , 4 , - 1 , - 2 ] ; var n = arr . length ; document . write ( maxAlternatingSum ( arr , n ) ) ;