- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

- while q is not empty and p > second value of last item of q, do
- return ans

Let us see the following implementation to get better understanding:

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))

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

[2, 1, 1, 0, 0, 0]

- Related Questions & Answers
- Program to find minimum number of days to make m bouquets using Python
- Program to find minimum number of operations required to make one number to another in Python
- Program to find minimum number of operations required to make lists strictly Increasing in python
- Program to find minimum number of characters to be added to make it palindrome in Python
- Program to find minimum number of operations required to make one string substring of other in Python
- Program to find minimum number of bricks required to make k towers of same height in Python
- Python program to find number of days between two given dates
- Program to find minimum number of deletions required from two ends to make list balanced in Python
- Program to find minimum bus fare for travelling all days in Python?
- Program to find minimum operations to make array equal using Python
- C++ Program to Find Minimum Number of Edges to Cut to make the Graph Disconnected
- Program to check minimum number of characters needed to make string palindrome in Python
- Program to count number of minimum swaps required to make it palindrome in Python
- Program to count minimum number of operations to flip columns to make target in Python
- Program to find minimum swaps required to make given anagram in python

Advertisements