题目描述
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).
分析:判断相邻是否递增,因为连续递增可以合起来看为一次买入卖出操作,所以统计所有递增量即可
class Solution {
public:
int maxProfit(vector<int> &prices) {
int max_profit=0;
int length=prices.size();
if(length==1)
return 0;
for(int i=1;i<length;i++){
int sum=prices[i]-prices[i-1];
if(sum>0)
max_profit += sum;
}
return max_profit;
}
};