best time to Buy and Sell Stock II
Say you has 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 could complete as many transactions as (ie, buy one and sell one share of the stock multiple times). However, engage in multiple transactions for the same time (ie, you must sell the stock before you buy again).
The core is to find all the monotonically increasing interval, and then sell to the simplest, whenever there is a price increase, sell out, accumulate all the proceeds (accept, but it seems to buy one and sell a share of the the stock multiple times)
1 classSolution {2 Public:3 intMaxprofit (vector<int> &prices) {4 5 intprofit=0;6 for(intI=1; I<prices.size (); i++)7 {8 if(prices[i]>prices[i-1])9 {Tenprofit+=prices[i]-prices[i-1]; One } A } - returnprofit; - the } -};
The following code finds the increment interval and then sells it on the last day
1 classSolution {2 Public:3 intMaxprofit (vector<int> &prices) {4 5 6 intprofit=0;7 intn=prices.size ();8 9 if(n==0)Ten { One return 0; A } - intbuyprice=prices[0]; - the for(intI=1; i<n;i++) - { - if(prices[i]<prices[i-1]) - { +profit+=prices[i-1]-Buyprice; -Buyprice=Prices[i]; + } A } at -profit+=prices[n-1]-Buyprice; - - returnprofit; - - } in};
"Leetcode" best time to Buy and Sell Stock II