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

121. Best Time to Buy and Sell Stock

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

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

 
public class Solution {
    public int maxProfit(int[] prices) {
        int maxProfit = 0;
        int lowestPrice = Integer.MAX_VALUE;
        
        for(int i = 0; i< prices.length; ++i)
        {
            if(prices[i]< lowestPrice)
                lowestPrice = prices[i];
            else{
                int currentProfit = prices[i] - lowestPrice;
                if(currentProfit > maxProfit)
                    maxProfit = currentProfit;
            }
        }
        
        return maxProfit;
    }
}

 

122. Best Time to Buy and Sell Stock II

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

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

 
public class Solution {
    public int maxProfit(int[] prices) {
        if(prices == null || prices.length <=1)
            return 0;
          
        int total = 0; 
        int last = prices[0];
        for(int i = 1;i<prices.length;++i)
        {
            if(prices[i]>last)
            {
                total+=prices[i]-last;
            }
            last = prices[i];
        }
        return total;
    }
}

 

123. Best Time to Buy and Sell Stock III

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 two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

 
public class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length == 0)
            return 0;
        //Get the max profit array if allow one transaction only.
        int[] maxProfitOneTransaction = new int[prices.length];
        maxProfitOneTransaction[0] = 0;
        int lowest = prices[0];
        
        for(int i = 1; i<prices.length; ++i)
        {
            if(prices[i]<lowest)
                lowest = prices[i];
            int currentMaxProfit = prices[i]-lowest;
            maxProfitOneTransaction[i] = Math.max(currentMaxProfit, maxProfitOneTransaction[i-1]);
        }
        
        int highest = Integer.MIN_VALUE;
        int totalMax = 0;
        for(int i = prices.length - 1; i>=0; --i)
        {
            if(prices[i]>highest)
                highest = prices[i];
            //Split current total max into two parts
            //Part 1 maxProfitOneTransaction[i]:
            //The first part is the max profit you can achieve from left to position i.
            //Part 2 highest-prices[i]:
            //The second part is the max profit you can achieve from position i to highest.
            int curTotalMax = maxProfitOneTransaction[i]+highest-prices[i];
            if(curTotalMax>totalMax)
                totalMax = curTotalMax;
        }
        return totalMax;
    }
}

 

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.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

First version of the algorithm, which has a TLE.
/**
 * dp[r, c] represents the max profit up to prices[c] with at most r transactions
 * dp[0, c] = 0. 0 transactions makes 0 profit
 * dp[r, 0] = 0. you can't make any transaction if there is only one price
 * <p>
 * To calculate dp[r,c], there are two cases to consider.
 * 1. Do nothing at c, or do NOT sell at prices[c]:
 * dp[r, c] = dp[r, c-1]
 * <p>
 * 2. Sell at prices[c], then it must be bought at b, such that b in [0, c-1]
 * dp[r, c]
 * = max(dp[r-1, b]+prices[c]-prices[b])
 * = prices[c] + max(dp[r-1, b]-prices[b])    where b in [0, c-1]
 * <p>
 * so, we have the formula for dp[r,c]
 * dp[r,c] = max(dp[r, c-1], prices[c] + max(dp[r-1, b]-prices[b]))
 */

class Solution {
  public int maxProfit(int k, int[] prices) {
    int len = prices.length;
    if (len <= 1)
      return 0;

    //if k >= len/2 is equivalent to make unlimited times of transactions.
    if (k >= len / 2) {
      int maxProfit = 0;
      for (int i = 1; i < len; ++i) {
        if (prices[i] > prices[i - 1])
          maxProfit += prices[i] - prices[i - 1];
      }
      return maxProfit;
    }

    int[][] dp = new int[k + 1][len];
    for (int r = 1; r <= k; ++r) {
      for (int c = 1; c < len; ++c) {
        int lastTransactionProfit = Integer.MIN_VALUE;
        for (int b = 0; b < c; ++b) {
          lastTransactionProfit = Math.max(lastTransactionProfit, dp[r - 1][b] - prices[b]);
        }
        dp[r][c] = Math.max(dp[r][c - 1], prices[c] + lastTransactionProfit);
      }
    }
    return dp[k][len - 1];
  }
}

Improve the algorithm above:

public class Solution {
  public int maxProfit(int k, int[] prices) {
    int len = prices.length;
    if (len <= 1)
      return 0;

    //if k >= len/2 is equivalent to make unlimited times of transactions.
    if (k >= len / 2) {
      int maxProfit = 0;
      for (int i = 1; i < len; ++i) {
        if (prices[i] > prices[i - 1])
          maxProfit += prices[i] - prices[i - 1];
      }
      return maxProfit;
    }

    int[][] dp = new int[k + 1][len];
    for (int r = 1; r <= k; ++r) {
      //lastTransactionProfit at (r-1,c) is the same for all cells at row r.
      //so we don't need to iterate through c, and redo this calculation.
      int lastTransactionProfit = dp[r - 1][0] - prices[0];
      for (int b = 1; b < len; ++b) {
        dp[r][b] = Math.max(dp[r][b - 1], prices[b] + lastTransactionProfit);
        lastTransactionProfit = Math.max(lastTransactionProfit, dp[r - 1][b] - prices[b]);
      }
    }
    return dp[k][len - 1];
  }
}

 

309. Best Time to Buy and Sell Stock with Cooldown

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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:

  • You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
  • After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)

Example:

prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]
 
This a DP problem that, we need to get the maximum profit from previous stage, and continue adding more profit.
The previous stage can end with 3 states : cooldown, buy/hold, sold.
cooldown -> buy/hold:  from cooldown, you can continue cooldown, or do a buy.
buy/hold -> sold: from buy/hold, you can continue hold, or do a sell.
sold -> cooldown: from sold, you can only do a cooldown.

 

 
In the end, the maximum profit is got from states ending with sold or cooldown.

class Solution {
  public int maxProfit(int[] prices) {
    int len = prices.length;
    if (len <= 1)
      return 0;
    int[] cooldown = new int[len]; //record max profit with state ending in cooldown
    int[] hold = new int[len];//record max profit with state ending in buy/hold
    int[] sold = new int[len];//record max profit with state ending in sell
    hold[0] = -prices[0];
    cooldown[0] = 0;
    sold[0] = Integer.MIN_VALUE;
    for (int i = 1; i < len; i++) {
      cooldown[i] = Math.max(
        cooldown[i - 1],//either continue cooldown
        sold[i - 1]//or just start cooldown
      );
      hold[i] = Math.max(
        hold[i - 1], //either continue holding
        cooldown[i - 1] - prices[i] //or buy at ith price.
      );
      sold[i] = hold[i - 1] + prices[i]; //sell at ith price
    }
    return Math.max(cooldown[len - 1], sold[len - 1]);
  }
}

Simplify the algorithm above:

public class Solution {
  public int maxProfit(int[] prices) {
    int len = prices.length;
    if (len <= 1)
      return 0;

    int sold = Integer.MIN_VALUE;
    int buy = -prices[0];
    int cooldown = 0;
    for (int i = 1; i < prices.length; ++i) {
      int prevSold = sold;
      sold = buy + prices[i];
      buy = Math.max(buy, cooldown - prices[i]);
      cooldown = Math.max(cooldown, prevSold);
    }
    return Math.max(sold, cooldown);
  }
}

 

 
 

转载于:https://www.cnblogs.com/neweracoding/p/5390752.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值