Best Time to Buy and Sell Stock II
My SubmissionsSay 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,2,3,1},因为2>1,盈利,所以买1钱卖2钱,因为3>2,所以买2钱卖3钱,其实这也相当于第一天买1钱,到第三天再卖3钱,一样,因为到第四天是亏本的,所以不去花3钱买第三天的股票了。
class Solution{
public:
int maxProfit(vector
&prices){
int maxP=0;
for(int i=1;i
0)maxP+=prices[i]-prices[i-1]; return maxP; } };