Получил этот вопрос в интервью сегодня, и его оптимизированное решение остановило меня холодно (что удары, потому что я действительно хотел работать для этой компании...)
Для одного массива реальных значений, каждый из которых представляет собой стоимость акций компании после произвольного периода времени, найдите лучшую цену покупки и соответствующую ему самую выгодную цену продажи (покупка низкая, высокая продажа).
Чтобы проиллюстрировать пример, позвольте взять биржевой тикер компании Z:
55.39 109.23 48.29 81.59 105.53 94.45 12.24
Важно отметить тот факт, что массив "сортируется" временно - т.е. с течением времени значения добавляются в правый конец массива. Таким образом, наша стоимость покупки будет (должна быть) слева от нашей стоимости продажи.
(в приведенном выше примере идеальным решением является покупка в 48.29
и продажа при 105.53
)
Я придумал наивное решение достаточно легко с сложностью O (n 2) (реализовано в 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) решение, и я полностью бомбил, пытаясь понять это (да, я знаю, FAIL). Кто-нибудь знает, как реализовать линейное решение времени? (любой язык, с которым вам удобно) Спасибо!
Изменить
Я полагаю, для всех, кого это интересует, я только что получил сегодня слово, что не получил работу, за которую я взял интервью, где они задали мне этот вопрос.: (