122_Best Time to Buy and Sell Stock II
Say you have an array for which the element is the price of a given stock on day i
.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).
Note:You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example:
Solution:
Idea:
catch all the valley and peak, add all the slope into profit
loop over all the elements, initiate
minprice
andmaxprice
as the first elementif the next element is larger than
maxprice
, updatemaxprice
with the current elementif the next element is smaller than
maxprice,
a new valley starts. Add the last profit into total profit and updateminprice
andmaxprice
be the current element.
Time Complexity:
Space Complexity:
Last updated