Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
思路:注意条件:在卖掉股票之前不能买下一只股票.总而言之,计算波浪线的上升区间
int maxProfit(vector<int> &prices) {
int result = 0;
int i = 0;
int len = prices.size();
if (len < 2)
return 0;
for (i = 1; i<len; ++i)
{
if (prices[i]>prices[i - 1])
{
result += prices[i] - prices[i - 1];
}
}
return result;
}
本文介绍了一种计算股票交易最大利润的算法。该算法允许进行多次买卖操作,但每次卖出后才能进行下一次购买。通过遍历价格数组,每当发现价格比前一天高时,就累加差价作为利润。
411

被折叠的 条评论
为什么被折叠?



