您的位置:首页 > 其它

最大收益

2016-06-01 16:02 387 查看
/*

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

*/

题意:

给定一系列价格(每天的),计算出最多能赚到多少钱,而且只能买卖一次。

多赚钱的原则就是低买高买,但要注意卖出一定要在买入之后。

* 方法一:只需要遍历一次价格。min=max=prices[0],不断置换最大的价格max,当出现比min小的价格时,计算这一轮的最大收益即max-min,如果比之前的收益更大,就更新最大收益。然后,重置min=price[i],max=min,开始新一轮的计算。最后,把max-min跟最大收益比较,返回最大收益。

#include <stdio.h>

int maxProfit(int* prices, int pricesSize) {

int min = prices[0], max = min;

int ret = 0;

for (int i = 1; i < pricesSize; i ++) {

if (min > prices[i]) {

ret = (max - min) > ret ? (max - min) : ret;

min = prices[i];

max = min;

}

else if (max < prices[i]) {

max = prices[i];

}

}

ret = (max - min) > ret ? (max - min) : ret;

return ret;

}

int main(int argc, char *argv[])

{

int arr[] = {5, 5, 6, 5, 4, 3, 5, 8, 3, 2, 5, 9};

printf("maxprofit: %d\n", maxProfit(arr, sizeof arr/sizeof arr[0]));

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: