动态规划-188. Best Time to Buy and Sell Stock IV

题目

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most k transactions.

题意解读:你有一个数组,第i个元素就是第i天的股票价格。你可以进行最多k次操作

/**
 * dp[i, j] represents the max profit up until prices[j] using at most i transactions. 
 * dp[i, j] = max(dp[i, j-1], prices[j] - prices[jj] + dp[i-1, jj]) { jj in range of [0, j-1] }
 *          = max(dp[i, j-1], prices[j] + max(dp[i-1, jj] - prices[jj]))
 *dp[i,j] = dp[i,j-1]表示第在第j天不做任何的交易
 *dp[i][j] = max(prices[j] - prices[jj] + dp[i-1, jj] { jj in range of [0, j-1] }) 表示第jj天买进股票,第j天卖出股票。完成第i次交易
 * dp[0, j] = 0; 0 transactions makes 0 profit
 * dp[i, 0] = 0; if there is only one price data point you can't make any transaction.
 */
class Solution {
    public int maxProfit(int k, int[] prices) {
        if(prices.length == 0)
            return 0;
        int n = prices.length;
        //分为两种情况,当k>=n/2时,可以进行最大次数的交易。就是随便买,随便卖
        if(k >= n/2){
            int maxPro = 0;
            for(int i = 1; i < n; i++)
                maxPro += (prices[i]>prices[i-1] ?prices[i]-prices[i-1]:0);
            return maxPro;
        }
        //第二种情况
        int[][] dp = new int[k+1][n];
        for(int i = 1; i <= k; i++ ){
            int localMax = dp[i-1][0] - prices[0];
            for(int j = 1; j < n; j++){
                dp[i][j] = Math.max(dp[i][j-1],prices[j]+localMax);
                localMax = Math.max(localMax,dp[i-1][j]-prices[j]);
            }
        }
        return dp[k][n-1];
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值