- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- 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:
Example
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]
Advertisements