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

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]

To solve this, we will follow these steps:

  • ans := a list of size same as prices and fill with 0
  • q := a new list
  • for each index i and price p in prices, do
    • while q is not empty and p > second value of last item of q, do
      • j := first item of last element of q
      • ans[j] := i - j
      • delete last element from q
    • insert (i, p) at the end of q
  • return ans

Let us see the following implementation to get better understanding:

Example

Live Demo

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

ob = Solution()
prices = [4, 3, 5, 9, 7, 6]
print(ob.solve(prices))

Input

[4, 3, 5, 9, 7, 6]

Output

[2, 1, 1, 0, 0, 0]
Updated on: 2020-11-26T08:18:33+05:30

268 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements