Maximize the happiness of the groups on the Trip | Function to return the maximized happiness ; Two arrays similar to 0 1 knapsack problem ; To store the happiness of the current goup ; Current person is a child ; Woman ; Man ; Old Person ; Group 's happiness is the sum of happiness  of the people in the group multiplie  the number of people ; Solution using 0 1 knapsack ; Number of seats ; Groups
function maxHappiness ( A , N , v ) { let str ; let val = Array . from ( { length : N } , ( _ , i ) => 0 ) ; let wt = Array . from ( { length : N } , ( _ , i ) => 0 ) ; let c = 0 ; for ( let i = 0 ; i < N ; i ++ ) { str = v [ i ] ; c = 0 ; for ( let j = 0 ; j < str . length ; j ++ ) { if ( str [ j ] == ' ' ) c += 4 ; else if ( str [ j ] == ' ' ) c += 3 ; else if ( str [ j ] == ' ' ) c += 2 ; else c ++ ; } c *= str . length ; val [ i ] = c ; wt [ i ] = str . length ; } let k = new Array ( N + 1 ) ; for ( var i = 0 ; i < k . length ; i ++ ) { k [ i ] = new Array ( 2 ) ; } for ( let i = 0 ; i <= N ; i ++ ) { for ( let w = 0 ; w <= A ; w ++ ) { if ( i == 0 w == 0 ) k [ i ] [ w ] = 0 ; else if ( wt [ i - 1 ] <= w ) { k [ i ] [ w ] = Math . max ( val [ i - 1 ] + k [ i - 1 ] [ w - wt [ i - 1 ] ] , k [ i - 1 ] [ w ] ) ; } else { k [ i ] [ w ] = k [ i - 1 ] [ w ] ; } } } return k [ N ] [ A ] ; } let A = 5 ; let v = [ " " , " " , " " , " " , " " ] ; let N = v . length ; document . write ( maxHappiness ( A , N , v ) ) ;