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

来源:互联网 发布:阿里云解析新网域名 编辑:程序博客网 时间:2024/06/05 06:52
题目

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];    }}


原创粉丝点击