Python: Calculate the maximum profit from selling and buying values of stock
Python Basic - 1: Exercise-74 with Solution
Write a Python program to calculate the maximum profit from selling and buying values of stock. An array of numbers represent the stock prices in chronological order.
For example, given [8, 10, 7, 5, 7, 15], the function will return 10, since the buying value of the stock is 5 dollars and sell value is 15 dollars.
Sample Solution:
Python Code:
def buy_and_sell(stock_price):
max_profit_val, current_max_val = 0, 0
for price in reversed(stock_price):
current_max_val = max(current_max_val, price)
potential_profit = current_max_val - price
max_profit_val = max(potential_profit, max_profit_val)
return max_profit_val
print(buy_and_sell([8, 10, 7, 5, 7, 15]))
print(buy_and_sell([1, 2, 8, 1]))
print(buy_and_sell([]))
Sample Output:
10 7 0
Flowchart:

Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to remove the duplicate elements of a given array of numbers such that each element appear only once and return the new length of the given array.
Next: Write a Python program to remove all instances of a given value from a given array of integers and find the length of the new array.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join