Topic:
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).
C++:
classSolution { Public: intMaxprofit (vector<int>&prices) {unsignedintI=0, profit=0; if(prices.size () = =0) { return 0; }Else { for(i=0; I<prices.size ()-1; i++) { if(prices[i+1]-prices[i]>0) {Profit+ = (prices[i+1]-Prices[i]); } } returnprofit; } }};
C:
intMaxprofit (int* Prices,intpricessize) { if(pricessize<=0)return 0; inttmp//initial error defines TMP as unsigned intUnsignedinti,profit=0; for(i=0;i< (pricessize-1); i++) {tmp=prices[i+1]-Prices[i]; if(tmp>0) {Profit+=tmp; } } returnprofit;}
best time to Buy and Sell Stock II