123 Best Time to Buy and Sell Stock III

题目链接: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).

解题思路:
这题的考点是动态规划
这题是 188 Best Time to Buy and Sell Stock IV 这题的特殊情况。即 k = 2 时。

代码实现:

public class Solution {
    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 = 1; i < prices.length; i ++) {
            int diff = prices[i] - prices[i - 1];
            for(int j = 2; j >= 1; j --) {
                local[j] = Math.max(global[j - 1] + Math.max(diff, 0), local[j] + diff);
                global[j] = Math.max(global[j], local[j]);
            }
        }
        return global[2];
    }
}
198 / 198 test cases passed.
Status: Accepted
Runtime: 9 ms
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
最佳的时间买卖股票III问题也可以使用动态规划算法来解决。动态规划算法通过将问题拆分为子问题,并利用子问题的解来构建更大规模问题的解。 对于最佳的时间买卖股票III问题,我们可以使用动态规划来构建一个二维数组dp,其中dp[i][j]表示在第i天结束时,最多进行j次交易所能获得的最大利润。 我们可以使用两个状态数组buysell来表示第j次交易的买入和卖出价格。初始化buysell数组为负无穷大。 接下来,我们遍历股票价格列表,对于每一天的价格,我们更新buysell数组的值。具体更新方式如下: 1. 对于第j次交易的买入价格,我们可以选择继续保持之前的买入价格(buy[j])或者在第i天买入(prices[i] - dp[i-1][j-1])。 2. 对于第j次交易的卖出价格,我们可以选择继续保持之前的卖出价格(sell[j])或者在第i天卖出(prices[i] + buy[j])。 在更新完buysell数组后,我们更新dp[i][j]为当前的最大利润(即sell[j])。 最后,我们返回dp[-1][-1]作为最大利润。 下面是使用动态规划算法解决最佳的时间买卖股票III问题的代码示例(假设prices是股票价格的列表): ```python def maxProfit(prices): n = len(prices) k = 2 # 最多进行两次交易 dp = [[0] * (k+1) for _ in range(n)] buy = [-float('inf')] * (k+1) sell = [0] * (k+1) for i in range(n): for j in range(1, k+1): buy[j] = max(buy[j], dp[i-1][j-1] - prices[i]) sell[j] = max(sell[j], prices[i] + buy[j]) dp[i][j] = max(dp[i-1][j], sell[j]) return dp[-1][-1] ``` 这个算法的时间复杂度是O(nk),其中n是股票价格列表的长度,k是最多进行的交易次数。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值