Best Time to Buy and Sell Stock | & || & III

Posted 北叶青藤

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Best Time to Buy and Sell Stock | & || & III相关的知识,希望对你有一定的参考价值。

Best Time to Buy and Sell Stock I

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.

Example

Given array [3,2,3,1,2], return 1.

分析:因为卖出总是在买入后,所以,只要有更低的买入价格,我们就可以更新买入价格,如果价格比买入价格低,我们就更新tempMax。看代码后即可明白。

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         if (prices == null || prices.length <= 1) return 0;
 4         
 5         int tempMax = 0;
 6         int buyPrice = prices[0];
 7         
 8         for (int i = 1; i < prices.length; i++) {
 9             if (prices[i] > buyPrice) {
10                 tempMax = Math.max(tempMax, prices[i] - buyPrice);
11             } else {
12                 buyPrice = prices[i];
13             }
14         }
15         return tempMax;
16     }
17 }

Best Time to Buy and Sell Stock II

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). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Example

Given an example [2,1,2,0,1], return 2

分析:既然允许unlimited 交易,那么,每个价格波峰都是卖出点,每个价格波谷都是买入点。

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         // corner cases
 4         if (prices == null || prices.length <= 1) return 0;
 5         int buyPrice = prices[0], totalProfit = 0;
 6         
 7         for (int i = 1; i < prices.length; i++) {
 8             if (prices[i] < prices[i - 1]) {
 9                 totalProfit += prices[i - 1] - buyPrice;
10                 buyPrice = prices[i];                
11             } 
12         }
13         
14         totalProfit += prices[prices.length - 1] - buyPrice;
15         return totalProfit;
16     }
17 }

 

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         return maxProfit(prices, 0);
 4     }
 5     
 6     public int maxProfit(int[] prices, int fee) {
 7         if (prices.length <= 1) return 0;
 8         int days = prices.length;
 9         int[] buy = new int[days];
10         int[] sell = new int[days];
11         
12         buy[0] = -prices[0] - fee;
13         for (int i = 1; i< days; i++) {
14              // keep the same as day i-1, or buy from sell status at day i-1
15             buy[i] = Math.max(buy[i - 1], sell[i - 1] - prices[i] - fee);
16             // keep the same as day i-1, or sell from buy status at day i-1
17             sell[i] = Math.max(sell[i - 1], buy[i - 1] + prices[i]); 
18         }
19         return sell[days - 1];
20     }
21 }

 

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.

Example

Given an example prices = [4,4,6,1,1,4,2,5], return 6.

分析:

既然题目说,最多只能交易两次,所以,可能是一次,也可能是两次。如果是只交易一次,那么我们就从开始点(0)到结束点(prices.length - 1) 找出只做一次交易的maxProfit. 如果只做两次,那么两次只能在 (0, k) 和 (k + 1, prices.length - 1) 产生,而k的范围是 0 <= k <= prices.length - 1.

 1 class Solution {
 2     /**
 3      * @param prices: Given an integer array
 4      * @return: Maximum profit
 5      * cnblogs.com/beiyeqingteng/
 6      */
 7     public int maxProfit(int[] prices) {
 8         if (prices == null || prices.length <= 1) return 0;
 9 
10         int max = 0;
11         for (int i = 0; i < prices.length; i++) {
12             if (i == prices.length - 1) {
13                 max = Math.max(max, maxProfit(prices, 0, i));
14             } else {
15                 max = Math.max(max, maxProfit(prices, 0, i) + maxProfit(prices, i + 1, prices.length - 1));
16             }
17         }
18         return max;
19     }
20     
21     // once one transaction is allowed from point i to j
22     private int maxProfit(int[] prices, int i, int j) {
23         if (i >= j) return 0;
24         int profit = 0;
25         
26         int lowestPrice = prices[i];
27         
28         for (int k = i + 1; k <= j; k++) {
29             if (prices[k] > lowestPrice) {
30                 profit = Math.max(profit, prices[k] - lowestPrice);
31             } else {
32                lowestPrice =  prices[k];
33             }
34         }
35         return profit;
36     }
37 };
View Code

 另一种方法,直接倒过来,考虑从当前到最后一天能够只做一次交易的时候,能够获取的最大利益。这种情况下,我们要找到最大的sellPrice.

 

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         if (prices == null || prices.length <= 1) return 0;
 4 
 5         int max = 0;
 6         int[] maxProfit = maxProfitForward(prices);
 7         int[] maxLoss = maxProfitBackward(prices);
 8         
 9         for (int i = 0; i < prices.length; i++) {
10             if (i == prices.length - 1) {
11                 max = Math.max(max, maxProfit[i]);
12             } else if (i == 0) {
13                 max = Math.max(max, maxLoss[i]);
14             } else {
15                 max = Math.max(max, maxProfit[i] + maxLoss[i]);
16             }
17         }
18         return max;
19     }
20     
21     // once one transaction is allowed from point i to j
22     private int[] maxProfitBackward(int[] prices) {
23         int sellPrice = prices[prices.length - 1];
24         int[] maxLoss = new int[prices.length];
25         int tempMin = 0;
26         
27         for (int i = prices.length - 2; i >= 0; i--) {
28             if (prices[i] < sellPrice) {
29                 tempMin = Math.max(tempMin, sellPrice - prices[i]);
30             } else {
31                 sellPrice = prices[i];
32             }
33             maxLoss[i] = tempMin;
34         }
35         return maxLoss;
36     }
37     
38     
39     private int[] maxProfitForward(int[] prices) {
40         int buyPrice = prices[0];
41         int[] maxProfit = new int[prices.length];
42         int tempMax = 0;
43         
44         for (int i = 1; i < prices.length; i++) {
45             if (prices[i] > buyPrice) {
46                 tempMax = Math.max(tempMax, prices[i] - buyPrice);
47             } else {
48                 buyPrice = prices[i];
49             }
50             maxProfit[i] = tempMax;
51         }
52         return maxProfit;
53     }
54 }

 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).

第一种方法:暴力解法

因为最多可以交易 k 次,在prices array里,我们总能够找到一个点 p, 从p + 1 到 prices array的最后一个元素,最多交易次数为1, 那么我们就可以递归调用原函数。

 1 public class Solution {
 2     public int maxProfit(int k, int[] prices) {
 3         return helper(k, prices, 0, prices.length - 1);
 4     }
 5     
 6     private int helper(int k, int[] prices, int start, int end) {
 7         if (start >= end || k == 0) return 0;
 8         if (k == 1) {
 9             int buyPrice = prices[start];
10             int maxProfit = 0;
11             for (int i = start + 1; i <= end; i++) {
12                 if (prices[i] > buyPrice) {
13                     maxProfit = Math.max(maxProfit, prices[i] - buyPrice);
14                 } else {
15                     buyPrice = prices[i];
16                 }
17             }
18             return maxProfit;
19         } else {
20             int max = 0;
21             for (int p = start; p <= end; p++) {
22                 max = Math.max(max, helper(k - 1, prices, start, p) + helper(1, prices, p + 1, end));
23             }
24             return max;
25         }
26     }
27 }

以上是关于Best Time to Buy and Sell Stock | & || & III的主要内容,如果未能解决你的问题,请参考以下文章

最强解析面试题:best-time-to-buy-and-sell-stock

最强解析面试题:best-time-to-buy-and-sell-stock

121. Best Time to Buy and Sell Stock

122. Best Time to Buy and Sell Stock II

123. Best Time to Buy and Sell Stock III***

LeetCode 121. Best Time to Buy and Sell Stock