问题
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