今天在面试中遇到了这个问题,它的优化解决方案让我感到崩溃(因为我真的很想在这家公司工作...)
给定一个实数数组,每个元素都代表一家公司在任意时间段后的股票价值,找出最佳购买价格及其相应的最佳售出价格(低买高卖)。
举个例子,我们来看 Company Z 的股票代码:
55.39 109.23 48.29 81.59 105.53 94.45 12.24
需要注意的重要事项是该数组在时间上是“排序”的,也就是随着时间的推移,数值会被附加到数组的右端。因此,我们的购买值必须在卖出值的左侧(这是必须的)。
(在上面的示例中,理想解决方案是以48.29
的价格购买,以105.53
的价格出售。)
我很容易地想到了一个O(n2)复杂度的朴素解决方案(用Java实现):
// returns a 2-element array: first element is the index in the argument array
// of the best buying price, and the second element is the index of the best
// selling price which, collectively, maximize the trading return
//
// if there is no favorable trading (e.g. prices monotonically fall), null is returned
public int[] maximizeReturn(ArrayList<Double> prices) {
int [] retval = new int[2];
int BUY = 0, SELL = 1;
retval[BUY] = retval[SELL] = -1; // indices of buy and sell prices, respectively
for (int i = 0; i < prices.size(); i++) {
for (int j = i + 1; j < prices.size(); j++) {
double difference = prices.get(j).doubleValue() -
prices.get(i).doubleValue();
if (difference > 0.0) {
if (retval[BUY] < 0 || difference > prices.get(retval[SELL]).doubleValue() -
prices.get(retval[BUY]).doubleValue()) {
retval[BUY] = i;
retval[SELL] = j;
}
}
}
}
return (retval[BUY] > 0 ? retval : null);
}
我犯了一个错误:有一个线性时间复杂度O(n)的解决方案,但我完全没能想出来(是的,我知道,失败了)。 有人知道如何实现这个线性时间复杂度的解决方案吗? (任何你熟悉的编程语言都可以)谢谢!
编辑
我想对于任何感兴趣的人来说,我今天刚收到消息,我没能得到那份工作,而他们就是在面试时问了我这个问题。 :(