Re: [討論] 令人印象深刻的遞迴問題?
咦...題目不是要求用遞迴嗎?
原po的作法看不太懂,貼出比較直觀的寫法(就是把迴圈轉換成遞迴orz)
void recursion(double* first,
double* last,
double* best_buy,
double* best_sell)
{
if (first != last)
{
double max_profit;
double buy_price;
recursion(first + 1, last, best_buy, best_sell);
max_profit = *best_sell - *best_buy;
buy_price = *first;
while (++first != last)
{
double sell_price = *first;
double pred_profit = sell_price - buy_price;
if (max_profit < pred_profit)
{
*best_buy = buy_price;
*best_sell = sell_price;
max_profit = pred_profit;
}
}
}
else
{
*best_buy = 0;
*best_sell = 0;
}
}
int main()
{
double price[] = {55.39, 109.23, 48.29, 81.59, 81.58, 105.53, 94.45, 12.24};
double best_buy, best_sell;
recursion(
price, price + sizeof(price) / sizeof(price[0]),
&best_buy, &best_sell);
printf("best buy:\t%f\nbest sell:\t%f\nmax profit:\t%f\n",
best_buy, best_sell, best_sell - best_buy);
return 0;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 123.204.92.148
推
04/02 18:14, , 1F
04/02 18:14, 1F
→
04/02 18:14, , 2F
04/02 18:14, 2F
→
04/02 18:37, , 3F
04/02 18:37, 3F
推
04/02 18:40, , 4F
04/02 18:40, 4F
→
04/02 18:40, , 5F
04/02 18:40, 5F
→
04/03 22:44, , 6F
04/03 22:44, 6F
→
04/03 22:44, , 7F
04/03 22:44, 7F
→
04/03 22:44, , 8F
04/03 22:44, 8F
→
04/03 22:44, , 9F
04/03 22:44, 9F
→
04/03 22:45, , 10F
04/03 22:45, 10F
→
04/03 22:45, , 11F
04/03 22:45, 11F
→
04/03 22:48, , 12F
04/03 22:48, 12F
討論串 (同標題文章)
完整討論串 (本文為第 5 之 9 篇):
討論
18
47