Showing posts with label linearTime. Show all posts
Showing posts with label linearTime. Show all posts

Wednesday, 19 October 2022

Best Time to Buy and Sell Stock with Cooldown

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

Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:

  • After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

 Example 1:  
 Input: prices = [1,2,3,0,2]  
 Output: 3  
 Explanation: transactions = [buy, sell, cooldown, buy, sell]  
 Example 2:  
 Input: prices = [1]  
 Output: 0  

In example 1:- We have an array of prices and transactions, before we move forward let's go back and see the main restrictions we have here. We can't buy a stock or sell it the next day, we have to have at least one day gap (Cooldown day).

Now let's go back to the example, where we buy for 1 and sell for 2, which means the profit of 1, and then we have a cooldown period and then we buy for 0 and then sell for 2 which means the profit of 2.

So the total output is 3 and let's see how we can solve this problem with linear time O(n).



The downside of this approach would be Time Complexity = height of the tree n, where n is the size of the prices array, and the number of decisions we can make at every step is 2 so the overall time complexity would be (2n)

Using a Dynamic programming technique called caching we can reduce the time complexity by O(n)

 State: Buying and selling  
 if buying => i+1  
 if selling => i+2 (remember we need to wait for the cooldown day so i+2)  





Happy Coding and Keep Sharing !!   Code Repo