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) {
vector<int>::iterator it = prices.begin();
if (prices.size() < 2)
return 0;
int res = 0;
while (it != prices.end() - 1 )
{
if (*it < *(it+1))
res += *(it+1) - *it;
it++;
}
return res;
}
};
本文探讨了在股票市场中通过频繁交易实现最大利润的方法。关键在于识别价格上升区间并计算其长度总和,实现盈利最大化。算法设计简单且有效。
305

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



