LeetCode 188. Best Time to Buy and Sell Stock IV

最多转k次 求最大利润

毫无思路 不妨来看之前的笔记:
利用二维DP去做
dp[i][j] is defined as maximum profit from at most i transactions using prices[0…j]
so what’s the transaction formula?
so on day j, we have two options: do nothing, that makes dp[i][j] = dp[i][j-1]
or we choose to sell the stock: in order to sell the stock on day j, we have to bought it on day[0~j-1]
since we can’t sure which day is the day to buy in, so we have to iterate through every day to get the maximum
so we have to get max(dp[i-1][t-1] + prices[j] - prices[t]) where t from 0 to j-1.

and also, we need to keep in mind that if k >= prices.length/2, this problem is the same as transaction as many times as you can…(so in our code, we will do things for situations like this)

class Solution {
    public int maxProfit(int k, int[] prices) {
        int len = prices.length;
        if (len <= 1) return 0; 
        if (k >= len / 2) {
            int profit = 0;
            for (int i = 1; i < len; i++) {
                int diff = prices[i] - prices[i-1];
                if (diff > 0) profit += diff;
            }
            System.out.println(profit);
            return profit;
        }
        
        //next is dp part:
        int[][] dp = new int[k+1][len];//keep in mind what dp[i][j] means
        
        //initialize here, however, dp[0][j] means most 0 transation: so all 0
        //dp[i][0] means no prices at all, so all 0 as well 
        
        //now we do not sure what we need to initialize, so we write the transaction equation:
        for (int i = 1; i <= k; i++) {
            int max = - prices[0]; //initialize max for every row, so max is overall max for each row
            for (int j = 1; j < len; j++) {
                dp[i][j] = Math.max(dp[i][j-1], prices[j] + max); 
                max = Math.max(max, dp[i-1][j-1] - prices[j]); //the j in max is actually j-1
            } //why this could work?
        }
        return dp[k][len - 1];
        
    }
}
posted @ 2020-11-21 09:37  EvanMeetTheWorld  阅读(21)  评论(0)    收藏  举报