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

本文详细探讨了不同约束条件下的股票买卖策略算法,包括仅能进行一次交易、可进行多次交易、最多两次交易及最多k次交易的情况,并提供了具体实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 }

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 }

转载于:https://www.cnblogs.com/beiyeqingteng/p/5628751.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值