Leetcode Best Time to Buy and Sell Stock with Transaction Fee, How to think in it

六眼飞鱼酱① 提交于 2019-12-25 01:45:28

问题


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


回答1:


Say the given array is:

[7, 1, 5, 3, 6, 4]

If we plot the numbers of the given array on a graph, we get:

Profit Graph

The points of interest are the peaks and valleys in the given graph. We need to find the largest peak following the smallest valley. We can maintain two variables - minprice and maxprofit corresponding to the smallest valley and maximum profit (maximum difference between selling price and minprice) obtained so far respectively.

class Solution {
  public int maxProfit(int[] prices) {
     int max = 0;
     int min = Integer.MAX_VALUE;

     for(int i = 0 ; i < prices.length ; i++) {
        if(prices[i] < min) {
            min = prices[i];
        }else {
            max = Math.max(max, prices[i] - min);
        }
     }

     return max; 
  }
}


来源:https://stackoverflow.com/questions/56405142/leetcode-best-time-to-buy-and-sell-stock-with-transaction-fee-how-to-think-in-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!