Program to find minimum number of days to wait to make profit in python

Suppose we have a list of prices representing the daily stock market prices of a company in chronological sequence. We have to find a same length list where the value at index i will be the minimum number of days we would have to wait until we make a profit. If there is no such way to make a profit, the value should be 0.

So, if the input is like prices = [4, 3, 5, 9, 7, 6], then the output will be [2, 1, 1, 0, 0, 0]

Algorithm

To solve this problem, we will use a stack-based approach:

  • ans := a list of size same as prices and fill with 0
  • stack := a new list to store indices and prices
  • for each index i and price p in prices, do
    • while stack is not empty and p > price of last item in stack, do
      • j := index of last element in stack
      • ans[j] := i - j (days to wait for profit)
      • remove last element from stack
    • insert (i, p) at the end of stack
  • return ans

Example

Let us see the following implementation to get better understanding:

class Solution:
    def solve(self, prices):
        ans = [0 for _ in prices]
        stack = []
        
        for i, p in enumerate(prices):
            while stack and p > stack[-1][1]:
                j = stack[-1][0]
                ans[j] = i - j
                stack.pop()
            stack.append((i, p))
        
        return ans

# Test the solution
ob = Solution()
prices = [4, 3, 5, 9, 7, 6]
result = ob.solve(prices)
print("Input prices:", prices)
print("Days to wait:", result)
Input prices: [4, 3, 5, 9, 7, 6]
Days to wait: [2, 1, 1, 0, 0, 0]

How It Works

The algorithm uses a monotonic stack to efficiently track prices that haven't found a profitable day yet:

  • For price 4 at index 0: No higher price found yet, remains in stack
  • For price 3 at index 1: Lower than 4, added to stack
  • For price 5 at index 2: Higher than 3, so index 1 waits 1 day (2-1=1)
  • For price 9 at index 3: Higher than 5 and 4, so index 2 waits 1 day, index 0 waits 2 days
  • Remaining prices (7, 6) never find higher prices, so they get 0

Alternative Implementation

Here's a simpler version without using a class:

def days_to_profit(prices):
    ans = [0] * len(prices)
    stack = []
    
    for i, price in enumerate(prices):
        while stack and price > prices[stack[-1]]:
            j = stack.pop()
            ans[j] = i - j
        stack.append(i)
    
    return ans

# Test with example
prices = [4, 3, 5, 9, 7, 6]
print(days_to_profit(prices))
[2, 1, 1, 0, 0, 0]

Conclusion

This problem uses a monotonic stack to efficiently find the next greater element for each price. The time complexity is O(n) since each element is pushed and popped at most once. The space complexity is O(n) for the stack and result array.

Updated on: 2026-03-25T12:52:41+05:30

322 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements