Longest alternating subsequence with maximum sum | Set 2 | Function to check the sign of the element ; Function to calculate and return the maximum sum of longest alternating subsequence ; Iterate through the array ; Stores the first element of a sequence of same sign ; Traverse until an element with opposite sign is encountered ; Update the maximum ; Update the maximum sum ; Update i ; Return the maximum sum ; Driver Code
function sign ( x ) { if ( x > 0 ) return 1 ; else return - 1 ; } function findMaxSum ( arr , size ) { let max_sum = 0 , pres , i , j ; for ( i = 0 ; i < size ; i ++ ) { pres = arr [ i ] ; j = i ; while ( j < size && sign ( arr [ i ] ) == sign ( arr [ j ] ) ) { pres = Math . max ( pres , arr [ j ] ) ; j ++ ; } max_sum = max_sum + pres ; i = j - 1 ; } return max_sum ; } let arr = [ - 2 , 8 , 3 , 8 , - 4 , - 15 , 5 , - 2 , - 3 , 1 ] ; let size = arr . length ; document . write ( findMaxSum ( arr , size ) ) ;