- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# 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

- Related Articles
- Program to find maximum profit we can make by buying and selling stocks in Python?
- Program to find maximum profit we can get by buying and selling stocks with a fee in Python?
- Program to find maximum profit we can make after k Buy and Sell in python
- C++ program to find maximum profit we can make by making hamburger and chicken burgers
- Program to find maximum profit by selling diminishing-valued colored balls in Python
- Program to find maximum profit after cutting rods and selling same length rods in Python
- Program to find the maximum profit we can get by buying on stock market once in Python
- Program to find maximum profit after buying and selling stocks at most two times in python
- Program to find the maximum profit we can get by buying on stock market multiple times in Python
- Maximum profit by buying and selling a share at most twice
- Program to get maximum profit by scheduling jobs in Python
- C++ Program to find out the maximum amount of profit that can be achieved from selling wheat
- Maximum profit after buying and selling the stocks in C++
- Program to find maximum price we can get by holding items into a bag in Python
- Program to find minimum number of days to wait to make profit in python

Advertisements