The max_profit
function calculates the maximum possible profit from a list of stock prices by iterating through the list and adding up the differences between each pair of consecutive prices. The function returns 0 as the total profit if the input list is empty, contains only one price, or has prices in descending order.
def max_profit(prices):
"""Find maximum profit possible."""
profit = 0
for i in range(len(prices)-1):
if prices[i+1] > prices[i]:
profit += prices[i+1] - prices[i]
return profit
assert max_profit([]) == 0
assert max_profit([100]) == 0
assert max_profit([1,6,5,2,8,1,4,5]) == 15
assert max_profit(range(100, 0, -1)) == 0
print('All passed')
def max_profit(prices):
"""
Find the maximum possible profit from a list of prices.
Args:
prices (list): A list of prices where each price is a positive integer.
Returns:
int: The maximum possible profit.
Raises:
ValueError: If prices is empty or contains non-positive values.
"""
if not prices:
raise ValueError("Prices cannot be empty")
for price in prices:
if price <= 0:
raise ValueError("All prices must be positive")
return sum(max(0, prices[i+1] - prices[i]) for i in range(len(prices)-1))
assert max_profit([]) == 0
assert max_profit([100]) == 0
assert max_profit([1,6,5,2,8,1,4,5]) == 15
assert max_profit(range(100, 0, -1)) == 0
# TODO: Implement a more efficient solution using a single pass through the prices list
# (currently has a time complexity of O(n^2))
def max_profit(prices):
max_profit
that takes one argument: prices
."""Find maximum profit possible."""
profit = 0
profit
and sets its value to 0. This variable will be used to store the total profit.for i in range(len(prices)-1):
prices
list.-1
is used to prevent an IndexError
when accessing prices[i+1]
.if prices[i+1] > prices[i]:
profit += prices[i+1] - prices[i]
prices[i+1]
) is greater than the current price (prices[i]
).return profit
assert max_profit([]) == 0
assert max_profit([100]) == 0
assert max_profit([1,6,5,2,8,1,4,5]) == 15
assert max_profit(range(100, 0, -1)) == 0
print('All passed')
max_profit
function with different input scenarios: