Best Time to Buy and Sell Stock II

This problem allows for buying and selling on the same day, and you can make as many transactions as you like. You will profit from buying and selling whenever the price of the stock increases from one day to the next.

Here’s the approach to this problem:

  1. Initialization: Initialize a variable max_profit to store the maximum profit. Set it to 0 initially.
  2. Iteration: Iterate through the prices array from the second element onwards.
    • For each price, check if it is greater than the previous day’s price.
    • If so, add the difference between the current price and the previous day’s price to max_profit.
  3. Result: max_profit holds the maximum profit that can be achieved.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # Initialize max_profit as 0
        max_profit = 0

        # Iterate through the prices from the second price onwards
        for i in range(1, len(prices)):
            # If the current price is greater than the previous price, profit can be made
            if prices[i] > prices[i - 1]:
                # Add the difference to max_profit
                max_profit += prices[i] - prices[i - 1]

        return max_profit

Key Takeaways:

  • The code identifies opportunities for profit by looking at the increase in price from one day to the next.
  • By buying and selling on the days when the price increases, you can achieve the maximum profit.
  • The time complexity of this solution is (O(n)), where (n) is the length of the prices array.
  • The space complexity is (O(1)), as we only use a constant amount of extra space.
  1. You may have few transactions to maximize the profit. We don’t have to maximize the transactions. We have to maximize the profit.

  2. If all numbers are decreasing, you cannot make any profit. If you cannot sell at a profit, return 0. Cannot return negative.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
def max_profit(prices)
    if prices.size < 2
        return 0
    end

    min = prices[0]
    profit = 0

    for i in (1..prices.size-1)
        new_profit = (prices[i] - min)
        profit = [new_profit, profit].max
        min = [min, prices[i]].min
    end

    profit
end
  1. Run a loop and keep checking If i is less than i+1 Calculate the difference between those two values (complete the transaction - profit) Accumulate the profit in a sum variable 0 1 2 3 4 5 [7,1,5,3,6,4]

    Scenarios to Buy/Sell 1-5 3-6

    Greedy approach

  2. We can have a profit variable intialized to 0

1
2
3
4
5
6
   for loop that runs from 0 to n-2
      if prices[i] < prices[i + 1]
         accumulate the profit, find the diff between 
         prices[i+1] - prices[i]

    return profit

Time: O(N) Space: O(1)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# @param {Integer[]} prices
# @return {Integer}
def max_profit(prices)
   n = prices.size
   profit = 0

   for i in (0..n-2)
      if (prices[i] < prices[i+1])
          profit += prices[i+1] - prices[i]
      end
   end
   return profit
end