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).
class Solution {
public:
int maxProfit(vector<int>& prices) {
int result = 0;
int profit = 0;
if (prices.size() < 2)
return result;
for (vector<int>::iterator it = prices.begin() + 1; it != prices.end(); ++it)
{
profit = *it - *(it-1);
if (profit > 0)
result += profit;
}
return result;
}
};
Personal Note:
实际上就是求所有上升区段的幅度和。

本文介绍了一种算法,用于在股票市场中寻找并利用价格波动实现最大利润。该算法允许无限次买卖股票,但每次交易后必须清空持股。通过分析价格序列,算法能够识别并累积所有上升趋势的收益。
304

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



