本文介绍了Leetcode最佳买卖交易时间的股票,如何思考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解有交易费的最佳买卖股票时间的解决方案,以及与股票出售有关的其他5个问题。我只是想深入了解如何在此类问题中建立这种递归关系。

I understand the solution to Best Time to Buy and Sell Stock with Transaction Fee, and other 5 problems relative to Stock Sell. I just want deep understanding of how to come up with such recursive relation in problems alike.

我已阅读,我完全理解。

I have read https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/108870/most-consistent-ways-of-dealing-with-the-series-of-stock-problems and I understand entirely.

但是,我在解决一些细微变化的类似问题时遇到了麻烦,例如

But, I am having trouble resolving some similar problem with minor changes, such as if one can buy stock without sell those previously bought first.

因此,得出正确的递归关系的一般方法是什么?

So, what is the general approach on coming up with correct recursive relation?

我真的很困惑。非常感谢

I am really confused. Thank you so much

推荐答案

 class Solution {
   public int maxProfit(int[] prices, int fee) {
    if (prices == null || prices.length <= 1) {
        return 0;
    } 
    long profit = 0, minPrice = Integer.MIN_VALUE;
    //Integer.MIN_VALUE = - 2147483648

  for (int price : prices) {
    long profit_old = profit;
    profit = Math.max(profit, minPrice + price - fee);
    minPrice = Math.max(minPrice, profit_old - price);  
   }  

  return (int)profit;

  }
}

您的输入[1,3, 2,8,4,9] 2

Your Input [1,3,2,8,4,9] 2

了解利润和利润如何minPrice值会在代码中更新

see how Profit & minPrice value gets updated in code

利润0。
minPrice -1

profit 0.minPrice -1

利润0
minPrice -1

profit 0minPrice -1

利润0
minPrice -1

profit 0minPrice -1

利润5
minPrice -1

profit 5minPrice -1

利润5
minPrice 1

profit 5minPrice 1

利润8
minPrice 1

profit 8minPrice 1

因此,最终MaxProfit为8。

So Final MaxProfit is 8.

这篇关于Leetcode最佳买卖交易时间的股票,如何思考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 06:08