【题目描述】
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
【解题思路】
一次遍历数组,只要递增,只要后一天的价格比前一天的大,就进行股票交易,从而累计利润。
【代码实现】
int maxProfit(int* prices, int pricesSize)
{
int j = 0;
int totalProfit = 0; //最大的利润
int curProfit = 0; //当次交易所得利润
if (NULL == prices || 0 >= pricesSize)
{
return 0;
}
for (j = 1; j < pricesSize; j++)
{
if (prices[j] > prices[j-1])
{
curProfit = prices[j] - prices[j-1];
totalProfit += curProfit;
}
}
return totalProfit;
}