<分区>
对于最大利润股票市场问题(使用 O(nlogn) 方法或 O(n) 方法),而不是返回数组 A 中给出最大利润的对,我如何返回一个数组给出数组 A 中每一天的最大利润?
最大利润可以定义为在第 i 天买入并在随后的一天卖出。
<分区>
对于最大利润股票市场问题(使用 O(nlogn) 方法或 O(n) 方法),而不是返回数组 A 中给出最大利润的对,我如何返回一个数组给出数组 A 中每一天的最大利润?
最大利润可以定义为在第 i 天买入并在随后的一天卖出。
最佳答案
你可以用 O(n)
的复杂度来做到这一点。这只是一次从左到右的传递。解决方案取自here .
public int getMaxProfit(int[] stockPricesYesterday) {
// make sure we have at least 2 prices
if (stockPricesYesterday.length < 2) {
throw new IllegalArgumentException("Getting a profit requires at least 2 prices");
}
// we'll greedily update minPrice and maxProfit, so we initialize
// them to the first price and the first possible profit
int minPrice = stockPricesYesterday[0];
int maxProfit = stockPricesYesterday[1] - stockPricesYesterday[0];
// start at the second (index 1) time
// we can't sell at the first time, since we must buy first,
// and we can't buy and sell at the same time!
// if we started at index 0, we'd try to buy /and/ sell at time 0.
// this would give a profit of 0, which is a problem if our
// maxProfit is supposed to be /negative/--we'd return 0!
for (int i = 1; i < stockPricesYesterday.length; i++) {
int currentPrice = stockPricesYesterday[i];
// see what our profit would be if we bought at the
// min price and sold at the current price
int potentialProfit = currentPrice - minPrice;
// update maxProfit if we can do better
maxProfit = Math.max(maxProfit, potentialProfit);
// update minPrice so it's always
// the lowest price we've seen so far
minPrice = Math.min(minPrice, currentPrice);
}
return maxProfit;
}
基本上,如果您对编写算法有疑问,我建议您先查看 GeekforGeeks ,这是一个很棒的门户。
关于arrays - 最大利润股市算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36990463/