Treasure and Cities | A memoization based program to find maximum treasure that can be collected . ; k is current index and col is previous color . ; if ( k == n ) base case ; check if color of this city is equal to prev visited city ; return max of both options ; Driver code
let MAX = 1001 ; let dp = new Array ( MAX ) ; for ( let i = 0 ; i < MAX ; i ++ ) { dp [ i ] = new Array ( MAX ) ; for ( let j = 0 ; j < MAX ; j ++ ) dp [ i ] [ j ] = - 1 ; } function MaxProfit ( treasure , color , n , k , col , A , B ) { return dp [ k ] [ col ] = 0 ; if ( dp [ k ] [ col ] != - 1 ) return dp [ k ] [ col ] ; let sum = 0 ; if ( col == color [ k ] ) sum += Math . max ( A * treasure [ k ] + MaxProfit ( treasure , color , n , k + 1 , color [ k ] , A , B ) , MaxProfit ( treasure , color , n , k + 1 , col , A , B ) ) ; else sum += Math . max ( B * treasure [ k ] + MaxProfit ( treasure , color , n , k + 1 , color [ k ] , A , B ) , MaxProfit ( treasure , color , n , k + 1 , col , A , B ) ) ; return dp [ k ] [ col ] = sum ; } let A = - 5 , B = 7 ; let treasure = [ 4 , 8 , 2 , 9 ] ; let color = [ 2 , 2 , 6 , 2 ] ; let n = color . length ; document . write ( MaxProfit ( treasure , color , n , 0 , 0 , A , B ) ) ;