Say you have an array for which the i th 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).
C++
class Solution {
public:
int maxProfit(vector<int>& prices){
int res = 0;
int n = prices.size() - 1;
for (int i = 0; i < n; ++i){
if (prices[i] < prices[i+1])
res += prices[i + 1] - prices[i];
}
return res;
}
};

本文介绍了一种计算股票交易最大利润的算法。该算法允许进行多次买卖操作,但每次卖出后才能再次购买。通过遍历价格数组并抓住每一次上涨机会来实现收益最大化。
602

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



