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). Compared to the best time to buy and Sell stock and the best time to buy and Sell the Stock III are simple, do not need to use dynamic planning, simply iterate through the array, encountered after a larger than the previous case, subtraction can be. Principle: Similar to greedy algorithm, buy at low price, sell at high price.
1 classSolution2 {3 Public:4 intMaxprofit (vector<int>prices)5 {6 if(Prices.empty ())7 return 0;8 9 intProfit =0;Ten for(intI=1; I<prices.size (); i++) One if(Prices[i] > prices[i-1]) AProfit + = Prices[i]-prices[i-1]; - - returnprofit; the } -};
best time to Buy and Sell Stock II