Maximum length Subsequence with alternating sign and maximum Sum | Function to find the subsequence with alternating sign having maximum size and maximum sum . ; Find whether each element is positive or negative ; Find the required subsequence ; Find the maximum element in the specified range ; prlet the result ; array declaration ; size of array
function findSubsequence ( arr , n ) { let sign = Array . from ( { length : n } , ( _ , i ) => 0 ) ; for ( let i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > 0 ) sign [ i ] = 1 ; else sign [ i ] = - 1 ; } let k = 0 ; let result = Array . from ( { length : n } , ( _ , i ) => 0 ) ; for ( let i = 0 ; i < n ; i ++ ) { let cur = arr [ i ] ; let j = i ; while ( j < n && sign [ i ] == sign [ j ] ) { cur = Math . max ( cur , arr [ j ] ) ; ++ j ; } result [ k ++ ] = cur ; i = j - 1 ; } for ( let i = 0 ; i < k ; i ++ ) document . write ( result [ i ] + " " ) ; document . write ( " " ) ; } let arr = [ - 4 , 9 , 4 , 11 , - 5 , - 17 , 9 , - 3 , - 5 , 2 ] ; let n = arr . length ; findSubsequence ( arr , n ) ;