122_Best Time to Buy and Sell Stock II
Last updated
Was this helpful?
Last updated
Was this helpful?
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).
Idea:
catch all the valley and peak, add all the slope into profit
loop over all the elements, initiate minprice
and maxprice
as the first element
if the next element is larger than maxprice
, update maxprice
with the current element
if the next element is smaller than maxprice,
a new valley starts. Add the last profit into total profit and update minprice
and maxprice
be the current element.
Time Complexity:
Space Complexity: