![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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 maximum profit we can make by holding and selling profit in Python
Suppose we have a list of numbers called nums, that is representing stock prices of a company in chronological order. We can buy at most one share of stock per day, but you can hold onto multiple stocks and can sell stocks on any number of days. Return the maximum profit you can earn.
So, if the input is like nums = [3, 4, 7, 3, 5], then the output will be 9, because we can buy the stocks at 3 and 4 and sell them at 7. Then again buy at 3 and sell at 5. Total profit (7 - 3) + (7 - 4) + (5 - 3) = 9.
To solve this, we will follow these steps −
- ans := 0
- while nums is not empty, do
- top := delete last element from nums
- while nums is not empty and top > last element of nums, do
- ans := ans + (top - last element from nums)
- delete last element from nums
- return ans
Example
Let us see the following implementation to get better understanding −
def solve(nums): ans = 0 while nums: top = nums.pop() while nums and top > nums[-1]: ans += top - nums.pop() return ans nums = [3, 4, 7, 3, 5] print(solve(nums))
Input
[3, 4, 7, 3, 5]
Output
9
Advertisements