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

Updated on: 14-Oct-2021

562 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements