战胜股市:现在欧美股市相当劲爆,你是不是心动了,假设给你一个数组表示这个月内每天谷歌股票的收盘价,还假设在这个月内,你只能在收盘时买或者卖一股谷歌股票,是的,就一股,你能设计一个算法寻找你最佳的买卖时间,赚取最多的钱?
思路:扫描数组,保存当前的最低价格和最好的盈利。当现在的价格和最低的价格的差值好于最好盈利,更新最好盈利。简单吧,同学们不要认为面试题都是难的,一般应该是难易结合,循序渐进,面试时保持平常心,保持最好的心态
附代码:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, lowestBuy = 0, highestSell = 0, lowestBuySoFar = 0;
int gain, maxGain = 0;
int prices[100];
printf("Please input the number of price: \n");
scanf("%d", &n);
for (i = 0; i < n; i++)
scanf("%d", &prices[i]);
for (i = 0; i < n; i++)
{
gain = prices[i] - prices[lowestBuySoFar];
if (gain > maxGain)
{
lowestBuy = lowestBuySoFar;
highestSell = i;
maxGain = gain;
}
if (prices[i] < prices[lowestBuySoFar])
lowestBuySoFar = i;
}
printf("Buy at the %d day at the price of %d, sell at the %d day at the price of %d\n", lowestBuy+1, prices[lowestBuy], highestSell+1, prices[highestSell]);
return 0;
}