ay 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).
由于不能同时进行多笔交易,该题考查数组中所有相邻且递增元素的数值之差的总和。只要第i+1天的值大于第i天的值,则可买入,求得利润(差值),遍历整个数组,得到所用差值之和即为总的利润。
int maxProfit(vector<int>& prices) {
if (prices.size() <= 1)
return 0;
int profit=0;
for(int i=0;i<prices.size()-1;i++){
if(prices[i+1]>prices[i])
profit+=prices[i+1]-prices[i];
}
return profit;
}