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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int count=prices.size();
int tmp=0;
int max=0;
for(int i=0 ; i<count-1 ; i++){
if((tmp=prices[i+1]-prices[i])>0)
max+=tmp;
}
return max;
}
};
本文介绍了一种用于计算股票交易最大利润的算法。该算法允许进行多次买卖操作但禁止同时持有多个股票。通过遍历价格数组,算法可以找出每次买入卖出能够获得正利润的机会,并累加这些利润得到最终的最大收益。
310

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



