Skip to main content
Practice

Finding Maximum Profit - Solution Explanation

Explore 3 ways to find the maximum profit.

Method 1
def solution(prices):
max_profit = 0

for i in range(len(prices) - 1):
for j in range(i + 1, len(prices)): # Buy at time i, sell at time j
profit = prices[j] - prices[i] # Calculate profit
max_profit = max(max_profit, profit) # Update maximum profit

return max_profit

Usage Example

Input/Output Example
result = solution([7, 1, 5, 3, 6, 4])

print(result) # Output: 5

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.