这道题由于可以不断地买卖,所以只要当前股票价格比前一次高了就可以加到profit里面去。
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int maxProfit(vector<int> &prices) {
if (prices.size() == 0)
{
return 0;
}
int profit = 0;
for (int i = 1; i < prices.size(); ++i)
{
if (prices[i] > prices[i - 1])
{
profit += prices[i] - prices[i - 1];
}
}
return profit;
}
};
int main()
{
std::vector<int> prices;
prices.push_back(1);
prices.push_back(2);
Solution s;
cout<<s.maxProfit(prices)<<endl;
return 0;
}