122. Best Time to Buy and Sell Stock II
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).
算法思路:
由于连续买的时候需要卖掉,也就是能持有1股,就是循环遍历如果明天比今天高,今买明卖就会受益,累加收益即可。
算法如下:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int i = prices.size();
int res = 0;
for(int j = 0; j < i-1; j++ ){
if(prices[j+1]>prices[j]){
res += prices[j+1] - prices[j];
}
}
return res;
}
};