You are given an integer array prices where prices[i] is the price of a given stock on the ith day.

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.

Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation:
buy stock on day 2 and sell on day 3, profit 5 - 1 = 4
buy stock on day 4 and sell on day 5, profit 6 - 3 = 3
So, total profit is 7.
Input: prices = [1,2,3,4,5]
Output: 4
Explanation:
buy stock on day 1 and sell on day 5, profit 5 - 1 = 4
So, total profit is 4.
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: Prices are decreasing in all days, so there is no way to make profit.

Contents

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 prices = [7, 1, 5, 3, 6, 4]

Problem 1 solution, step 1

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 ith day price is greater than i-1th day price, then we take that profit and repeat this until the end of array and return profit sum as answer.

public class BestTimeToBuyAndSellStockII { static int maxProfit(int[] prices) { int profit = 0; for(int i=1; i<prices.length; i++) { if(prices[i] >prices[i-1]) { profit += prices[i] - prices[i-1]; } } return profit; } }
Complexity Analysis:

Time complexity: Above code runs in O(n) time where n is the length of prices array.
Space complexity: O(1)

Above implementations source code can be found at GitHub link for Java code