Title Description
Given an array, the first element of it is the price of the first day of a given stock.
Design an algorithm to calculate the maximum profit you can get. You can do as many trades as possible (buy and sell a stock).
Note: You cannot participate in multiple transactions at the same time (you must sell the prior stock before buying again).
Example 1:
Input: [7,1,5,3,6,4] Output: 7 explanation: Buy on the 2nd day (stock price = 1), Sell on the 3rd day (stock price = 5), the trade can get Profit = 5-1 = 4. then, on the 4th day (stock price = 3) to buy, on the 5th day (stock price = 6) of the time to sell, the transaction can obtain Profit = 6-3 = 3.
Example 2:
Input: [1,2,3,4,5] Output: 4 explanation: Buy on the 1th day (stock price = 1), Sell on the 5th day (stock price = 5), the trade can get Profit = 5-1 = 4. Note that you cannot buy stocks on the 1th and 2nd days, and then sell them. since this is part of a multiple transaction, you must sell the stock before you buy it again.
Example 3:
Input: [7,6,4,3,1] Output: 0 explanation: In this case, no transaction is completed, so the maximum profit is 0.
Thinking of solving problems
Record the last buy stock price, when the current price is lower than the previous day, indicating that the holding will lose money, so the stock should be sold before the same date, and then re-buy, if the current price is higher than the previous price, then continue to hold. Finally, the last day's price minus the last buy price, added to the profit.
Code
1 classSolution {2 Public:3 intMaxprofit (vector<int>&prices) {4 if(Prices.size () <2)return 0;5 intMaxPro =0, last = prices[0];6 for(inti =1; I < prices.size (); i++){7 if(Prices[i] < prices[i-1]){8MaxPro + = prices[i-1] -Last ;9Last =Prices[i];Ten } One } AMaxPro + = Prices[prices.size ()-1] -Last ; - returnMaxPro; - } the};
Leetcode 122. Best timing for buying and selling Stocks II (prime time to Buy and Sell Stock II)