当前位置:   article > 正文

LeetCode123——买卖股票的最佳时机III_123. 买卖股票的最佳时机 iii python

123. 买卖股票的最佳时机 iii python

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/description/

题目描述:

知识点:动态规划

思路一:分解成两个LeetCode121——买卖股票的最佳时机子问题

枚举第一笔交易卖出的时间firstDealSell,对[0, firstDealSell]范围内的价格求解LeetCode121——买卖股票的最佳时机中的问题,得到结果result1,再对[firstDealSell, n - 1]范围内的价格再一次求解LeetCode121——买卖股票的最佳时机中的问题,其中n为prices数组的大小,得到结果result2,求result1 + result2的最大值。

时间复杂度是O(n ^ 2)。空间复杂度是O(1)。

当然,在此基础之上,结合LeetCode122——买卖股票的最佳时机II,我们可以做一些小小的优化。

对于第一次和第二次卖出的时间点,firstDealSell和secondDealSell,其之前的价格一定是一个上坡,其之后的价格一定是一个下坡,我们在价格坡顶卖出。

JAVA代码:

  1. public class Solution {
  2. public int maxProfit(int[] prices) {
  3. int result = 0;
  4. if(prices.length == 0){
  5. return result;
  6. }
  7. int firstDealSell; //第一笔交易在firstDealSell卖出
  8. int secondDealSell; //第二笔交易在secondDealSell卖出
  9. for(secondDealSell = prices.length - 1; secondDealSell > 0; secondDealSell--){
  10. if(prices[secondDealSell - 1] < prices[secondDealSell]){
  11. break;
  12. }
  13. }
  14. for(firstDealSell = 1; firstDealSell < prices.length; firstDealSell++){
  15. while(firstDealSell + 1 < prices.length && prices[firstDealSell + 1] >= prices[firstDealSell]){
  16. firstDealSell++;
  17. }
  18. int result1 = maxProfit(prices, 0, firstDealSell);
  19. int result2 = maxProfit(prices, firstDealSell &
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/499937
推荐阅读
相关标签
  

闽ICP备14008679号