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
import java . util . * ; class GFG { static int MAX = 1001 ; static int [ ] [ ] dp = new int [ MAX ] [ MAX ] ; static int MaxProfit ( int treasure [ ] , int color [ ] , int n , int k , int col , int A , int B ) { return dp [ k ] [ col ] = 0 ; if ( dp [ k ] [ col ] != - 1 ) return dp [ k ] [ col ] ; int 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 ; } public static void main ( String [ ] args ) { int A = - 5 , B = 7 ; int treasure [ ] = { 4 , 8 , 2 , 9 } ; int color [ ] = { 2 , 2 , 6 , 2 } ; int n = color . length ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < MAX ; j ++ ) dp [ i ] [ j ] = - 1 ; System . out . print ( MaxProfit ( treasure , color , n , 0 , 0 , A , B ) ) ; } }