对于最大利润股市问题(使用O(nlogn)方法或O(n)方法),而不是返回给出最大利润的数组A中的对,我如何返回给出的数组数组A中每天的最大利润?
最大利润可以定义为在第i天购买并在随后的一天销售。
答案 0 :(得分:0)
您可以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查看,这是一个很棒的门户网站。