best-time-to-buy-and-sell-stock-ii.dart (875B)
1 //Given a list of prices and a maximum number of stocks owned at a time as 0 2 //return the max amount of money you can make by the end of the week assuming 3 //you can buy and sell on any day. This is the brute force recursive solution 4 //I will optimize this with memoization to beat the problem. 5 //Time: TLE 6 //Memory: TLE 7 class Solution { 8 int maxProfit(List<int> prices) { 9 return max(prices, 0, 0); 10 } 11 int max (List<int> prices, int owned, int val){ 12 if(prices.length == 0){ 13 return val; 14 } 15 int buy_or_sell = 0; 16 if(owned == 1){ 17 buy_or_sell = max(prices.sublist(1), 0 , val + prices[0]); 18 } 19 else{ 20 buy_or_sell = max(prices.sublist(1), 1, val - prices[0]); 21 } 22 int hold = max(prices.sublist(1) , owned, val); 23 24 if(buy_or_sell > hold){ 25 return buy_or_sell; 26 } 27 return hold; 28 } 29 }