Title Description:
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).
Problem Solving Ideas:
Greedy algorithm: The profit is updated as long as the current value is smaller than the previous value.
1 classSolution {2 Public:3 intMaxprofit (vector<int>&prices) {4 if(prices.size () = =0|| Prices.size () = =1) {5 return 0;6 }7 8 intMin_index =0;9 intProfit =0;Ten One for(inti =1; I < prices.size (); ++i) { A if(Prices[i] < prices[i-1]) { -Profit + = prices[i-1]-Prices[min_index] >0? Prices[i-1]-Prices[min_index]:0; -Min_index =i; the } - } - if(Prices[min_index] < prices[prices.size ()-1]) { -Profit + = Prices[prices.size ()-1] -Prices[min_index]; + } - + returnprofit; A } at};
[Leetcode] best time to Buy and Sell Stock II