You are given an integer array
On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.
Find and return the maximum profit you can achieve.
Output: 7
Explanation:
buy stock on day 2 and sell on day 3, profit
buy stock on day 4 and sell on day 5, profit
So, total profit is 7.
Output: 4
Explanation:
buy stock on day 1 and sell on day 5, profit
So, total profit is 4.
Output: 0
Explanation: Prices are decreasing in all days, so there is no way to make profit.
Contents
Solution 1 - Sell and Buy whenever there is a profit
As per the problem statement we can sell buy as many time as we want, so in this approach we are going to sell if there is any profit from previous day, meaning that if current day price is more than previous day, we sell it and assume we only bought if current day is price is higher than previous day.
For example consider this example with stock prices

If you see above graph, there is profits between day 2 and 3 and day 4 and 5,
so what we will do is if
Complexity Analysis:
Time complexity: Above code runs in O(n) time where
Space complexity: O(1)
Above implementations source code can be found at