LeetCode Best Time to Buy and Sell Stock III

本文探讨了在股票市场中通过最多进行两次交易实现最大收益的算法。通过维护全局最优和局部最优策略,文章详细解释了如何在特定日期进行买卖操作以最大化利润。此外,介绍了两种优化空间复杂度的方法,以及实现这些策略的ACJava代码。

原题链接在这里:https://leetcode.com/problems/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). 

题解:

本题是Best Time to Buy and Sell Stock的进阶版。思路也很相似,仍旧是维护一个全局最优,一个局部最优。

这里最多可以进行k次交易,就是Best Time to Buy and Sell Stock IV然后本题把k变成2即可。

全局最优global是到达第i天可以最多进行j次交易的利润是多少,局部最优local是必须在第i天进行最后一次交易的利润。

先更新局部最优:

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

diff是今天与昨天的差价, global[i-1][j-1] + max(diff,0)是指到第i-1天最多进行j-1次交易时的利润,加上进天得最后一次交易。

后一项是local[i-1][j] + diff是指在i-1天就进行了最多j次交易,i天进行最后一次交易,原本是i-1天卖的现在变成i天卖。

然后是更新全局变量:

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

比较前一天的全局最优和当天的局部最优,取大的那一个。

Method 2用了降维方法节省空间。

但是注意双重loop 的内层loop, j是从k向小变到1, 因为一维空间只能保存当前一行内容,更新local时用到了了global[i-1][j-1].

若是从前往后走到了i, j时,[i-1][j-1]会被[i][j-1]覆盖掉,所以要从后往前走。

Method 1 Time Complexity: O(prices.length * k), k是最多交易次数,这里k=2. Space: O(prices.length*k).

Method 2 Time Complexity: O(prices.length * k). Space: O(k).

AC Java:

 1 public class Solution {
 2     public int maxProfit(int[] prices) {
 3         return helper(prices,2);
 4     }
 5     private int helper(int[] prices, int k){
 6         if(prices == null || prices.length == 0){
 7             return 0;
 8         }
 9         /*
10         //Method 1
11         int[][] local = new int[prices.length][k+1];
12         int[][] global = new int[prices.length][k+1];
13         for(int i = 1; i<prices.length; i++){
14             int diff = prices[i]-prices[i-1];
15             for(int j = 1; j<=k; j++){
16                 local[i][j] = Math.max(global[i-1][j-1] + Math.max(diff,0), local[i-1][j]+diff);
17                 global[i][j] = Math.max(global[i-1][j], local[i][j]);
18             }
19         }
20         return global[prices.length-1][k];
21         */
22         
23         //Method 2
24         int [] local = new int[k+1];
25         int [] global = new int[k+1];
26         for(int i = 1; i<prices.length; i++){
27             int diff = prices[i]-prices[i-1];
28             for(int j = k; j>=1; j--){
29                 local[j] = Math.max(global[j-1] + Math.max(diff,0), local[j]+diff);
30                 global[j] = Math.max(global[j], local[j]);
31             }
32         }
33         return global[k];
34     }
35 }

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4824945.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值