121.Best Time to Buy and Sell Stock&&122&&123&&188

只能进行一次交易,当进行到第i天时,该天进行交易的话,最大利润为nums[i]-min{nums[j]},其中0<=j<=i-1.程序如下:

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length == 0) return 0;
        
        int maximum = 0;
        int currentMin = prices[0];
        
        for(int i = 1; i < prices.length; i++){
            if(prices[i] > currentMin) maximum = (prices[i]-currentMin > maximum) ? prices[i]-currentMin : maximum;
            else currentMin = prices[i];
        }
        
        return maximum;
    }
}

这题中,不限制交易的次数,考虑nums的图像,有的为上升段,有的为下降段,可以知道,在上升段的初始和结束位置进行交易获益最多,并且最终的利润等于改区间内当天买进,第二天卖出的利润的总和。代码如下:

class Solution {
    public int maxProfit(int[] prices) {
        int maxSoFar=0;
        int length = prices.length;
        
        for(int i=1; i<length; i++) {
            maxSoFar += Math.max(0, prices[i] - prices[i-1]);
        }
        return maxSoFar;
        
    }
}

这里我们先解释最多可以进行k次交易的算法,然后最多进行两次我们只需要把k取成2即可。我们还是使用“局部最优和全局最优解法”。我们维护两种量,一个是当前到达第i天可以最多进行j次交易,最好的利润是多少(global[i][j]),另一个是当前到达第i天,最多可进行j次交易,并且最后一次交易在当天卖出的最好的利润是多少(local[i][j])。下面我们来看递推式,全局的比较简单,

global[i][j]=max(local[i][j],global[i-1][j]),

也就是去当前局部最好的,和过往全局最好的中大的那个(因为最后一次交易如果包含当前天一定在局部最好的里面,否则一定在过往全局最优的里面)。对于局部变量的维护,递推式是

local[i][j]=max(global[i-1][j-1]+max(diff,0),local[i-1][j]+diff),

也就是看两个量,第一个是全局到i-1天进行j-1次交易,然后加上今天的交易,如果今天是赚钱的话(也就是前面只要j-1次交易,最后一次交易取当前天),第二个量则是取local第i-1天j次交易,然后加上今天的差值(这里因为local[i-1][j]比如包含第i-1天卖出的交易,所以现在变成第i天卖出,并不会增加交易次数,而且这里无论diff是不是大于0都一定要加上,因为否则就不满足local[i][j]必须在最后一天卖出的条件了)。
上面的算法中对于天数需要一次扫描,而每次要对交易次数进行递推式求解,所以时间复杂度是O(n*k),如果是最多进行两次交易,那么复杂度还是O(n)。空间上只需要维护当天数据皆可以,所以是O(k),当k=2,则是O(1)。代码如下:

public int maxProfit(int[] prices) {
    if(prices==null || prices.length==0)
        return 0;
    int[] local = new int[3];
    int[] global = new int[3];
    for(int i=0;i<prices.length-1;i++)
    {
        int diff = prices[i+1]-prices[i];
        for(int j=2;j>=1;j--)
        {
            local[j] = Math.max(global[j-1]+(diff>0?diff:0), local[j]+diff);
            global[j] = Math.max(local[j],global[j]);
        }
    }
    return global[2];
}

如果不用动态规划,还有两种思路,一种是求出0-i天进行一次交易,i-n天进行一次交易,两次交易之和的最大值即为所求(我们可以划分为2个区间[0,i]和[i,len-1],i可以取0~len-1。那么两次买卖的最大利润为:在两个区间的最大利益和的最大利润。一次划分的最大利益为:Profit[i] = MaxProfit(区间[0,i]) + MaxProfit(区间[i,len-1]);最终的最大利润为:MaxProfit(Profit[0], Profit[1], Profit[2], ... , Profit[len-1])。)。程序如下:

 public int maxProfit(int[] prices) {  
 2         if(prices == null || prices.length <= 1){  
 3             return 0;  
 4         }  
 5         int len = prices.length;  
 6         int maxProfit = 0;  
 7         int min = prices[0];  
 8         int arrayA[] = new int[len];  
 9         
10         for(int i=1;i<prices.length;i++){
11             min=Math.min(min,prices[i]);
12             arrayA[i]=Math.max(arrayA[i-1],prices[i]-min);
13         }
14         
15         int max = prices[len-1];  
16         int arrayB[] = new int[len];  
17         for(int i = len-2; i >= 0; i--){
18             max = Math.max(prices[i],max);
19             arrayB[i] = Math.max(max-prices[i],arrayB[i+1]);
20         }  
21         
22         for(int i = 0; i < len; i++){  
23             maxProfit = Math.max(maxProfit,arrayA[i] + arrayB[i]);
24         }  
25         
26         return maxProfit;  
27     } 

第二种思路是在第一次进行交易后,将该次的盈利看成第二次交易买入的成本(从代数表达式来看,第二次的收益就包含了第一次交易的收益)。程序如下:

 

class Solution {
    public int maxProfit(int[] prices) {
        int buy1 = Integer.MAX_VALUE, buy2 = Integer.MAX_VALUE;
        int sell1 = 0, sell2 = 0;

        for (int i = 0; i < prices.length; i++) {
            buy1 = Math.min(buy1, prices[i]);
            sell1 = Math.max(sell1, prices[i] - buy1);
            buy2 = Math.min(buy2, prices[i] - sell1);
            sell2 = Math.max(sell2, prices[i] - buy2);
        }

        return sell2;
        
    }
}
class Solution {
    public int maxProfit2(int[] prices) {
        if(prices == null || prices.length < 2) return 0;
        int buy1 = Integer.MAX_VALUE;
        int afterSell1 = 0;
        int afterBuy2 = Integer.MIN_VALUE;
        int afterSell2 = 0;
        for(int p : prices){
            // 第一次买入价格,越小越好,和视频里的“借钱买”的意思是一样
            buy1 = Math.min(buy1, p);
            // 第一次卖出后获得的利润,越大越好
            afterSell1 = Math.max(afterSell1, p - buy1);
            // 用第一次交易的利润做第二次买入后获得的利润,越大越好
            afterBuy2 = Math.max(afterBuy2, afterSell1 - p);
            // 第二次卖出后获得的利润,越大越好
            afterSell2 = Math.max(afterSell2, afterBuy2 + p);
        }
        
        return afterSell2;
    }
    
    
    public int maxProfit(int prices[]) {
        if (prices == null || prices.length == 0) {
            return 0;
        }
        
        int K = 2;
        int T[][] = new int[K+1][prices.length];

        for (int i = 1; i < T.length; i++) {
            int maxDiff = -prices[0];
            for (int j = 1; j < T[0].length; j++) {
                T[i][j] = Math.max(T[i][j-1], prices[j] + maxDiff);
                maxDiff = Math.max(maxDiff, T[i-1][j] - prices[j]);
            }
        }
        return T[K][prices.length-1];
    }
}

这道题和123的解法很像,关键在于一个特殊情况,k比较大,如果不特殊处理,内存会爆的。当k>len/2时,也就相当于不限次数时的解法122。这很重要!!!

class Solution {
    public int maxProfit(int k, int[] prices) {
       /**
 * 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[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.
 */

        int n = prices.length;
        if (n <= 1)
            return 0;

        //if k >= n/2, then you can make maximum number of transactions.
        if (k >=  n/2) {
            int maxPro = 0;
            for (int i = 1; i < n; i++) {
                if (prices[i] > prices[i-1])
                    maxPro += prices[i] - prices[i-1];
            }
            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];
    }
}
class Solution {
    public int maxProfit(int k, int[] prices) {
        if (k == 0 || prices.length <= 0) {
            return 0;
        }
        
        if (k > prices.length / 2) {
            return maxProfitIfAny(prices);
        }
        
        int[] dp = new int[prices.length];
        int max = 0;
        for (int i = 1; i <= k; i++) {
            int minBuy = -prices[0];
            for (int j = 1; j < prices.length; j++) {
                int tmp = dp[j];
                dp[j] = Math.max(dp[j - 1], prices[j] + minBuy);
                minBuy = Math.max(tmp - prices[j], minBuy);
                max = Math.max(max, dp[j]);
            }
        }
        
        return max;
    }
    
    private int maxProfitIfAny(int[] prices) {
        int profit = 0;
        for (int i = 1; i < prices.length; i++) {
            profit += Math.max(0, prices[i] - prices[i - 1]);
        }
        return profit;
    }
}
public class Solution {
    
    // Time complexity: O(kn) where k is k, n is the number of prices
    // Space complexity: O(kn)
    public int maxProfit(int k, int[] prices) {
        int n = prices.length;
        if (k >= n/2) {
            // fast case because there are [0, n/2] continuous increases
            int maxProfit = 0;
            for (int i = 1; i < n; i++) {
                int diff = prices[i] - prices[i-1];
                if (diff > 0) {
                    maxProfit += diff;
                }
            }
            return maxProfit;
        }
        
        // Each element dp[i][j] means the max profit of at most i transactions until day j
        int[][] dp = new int[k+1][n];
        int localMax = Integer.MIN_VALUE;
        for (int i = 1; i <= k; i++) {
            for (int j = 1; j < n; j++) {
                localMax = Math.max(localMax, dp[i-1][j-1] - prices[j-1]);
                dp[i][j] = Math.max(dp[i][j-1], localMax + prices[j]);
            }
            localMax = Integer.MIN_VALUE;
        }
        return dp[k][n-1];
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值