HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

Buy once and sell once for maximum profit

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
oncemaximumbuysellforprofitand

Problem

Suppose we have stock price history, and we are allowed to buy only once and sell only once. The problem is to find the maximum profit we can make. Here is my code that I tested for basic test cases. I'm wondering if there are possible improvements for logic correctness.

My major idea is to keep record of in history minimal price, and determine if sell today (with the purchase of historical minimal price), whether we can make a larger profit.

prices = [100, 113, 110, 85, 105, 102, 86, 63, 81, 101, 94, 106, 101, 79, 94, 90, 97]
result = 0
minSofar = prices[0]
for i in range(1, len(prices)):
    minSofar = min(minSofar, prices[i])
    result = max (result, prices[i] - minSofar)

print result

Solution

profit would be a better name than result.

This could be simplified to a one-liner using itertools.combinations()

profit = max(sell - buy for buy, sell in itertools.combinations(prices, 2))

Code Snippets

profit = max(sell - buy for buy, sell in itertools.combinations(prices, 2))

Context

StackExchange Code Review Q#138088, answer score: 11

Revisions (0)

No revisions yet.