From what I understand, I believe you have to rephrase and adjust the problem into code. My observations based on the examples and expected results:
- The buying price is in the input list and has to be identified
- The selling price is also in the input list and has to be identified
- The buying price must be less than selling price
- The profit is the output and thus is
buying-selling
Now, converting this to an algorithm:
Attempt 1 (wrong in some cases - see comments)
- Find the minimum in the list - this is our buying price
- Find the maximum in the list that is on the "same or later day" ie. the index is the same or larger than the buying price index
The code (single executable - you need to make it a function if needed):
#!/usr/bin/env python
import sys
# Not part of the algorithm: converts first argument to a list of integers
prices = map(int, sys.argv[1].split(","))
# Find the best buying price
buy = min(prices)
# Find the best buying time/index
buyidx = prices.index(buy)
# Now the best selling price is the next maximum
sell = max(prices[buyidx:])
print(" Input: %s" % str(prices))
print("Output: %d" % (sell-buy))
Examples:
$ /tmp/stock.py 1,2,4
Input: [1, 2, 4]
Output: 3
$ /tmp/stock.py 7,1,5,3,6,4
Input: [7, 1, 5, 3, 6, 4]
Output: 5
$ /tmp/stock.py 1,2,3,4,5
Input: [1, 2, 3, 4, 5]
Output: 4
$ /tmp/stock.py 4,3,2
Input: [4, 3, 2]
Output: 0
$ /tmp/stock.py 4,3,1
Input: [4, 3, 1]
Output: 0
$ /tmp/stock.py 4,3,5
Input: [4, 3, 5]
Output: 2
Attempt 2 based on @kazemakase input
- The buying price is in the list but is not necessarily the minimum value. It is the value that maximizes the profit!
- For every day, calculate what our profit would be if we buy the stock that day - The selling price is the max value with index greater than the current day
- (@kazemakase) Loops are sometimes inevitable
The code:
#!/usr/bin/env python
import sys
prices = map(int, sys.argv[1].split(","))
# For every day
buy_final = 0
sell_final = 0
max_profit = 0
for (buyindex, buy) in enumerate(prices):
sell = max(prices[buyindex:])
profit = sell - buy
if profit > max_profit:
max_profit = profit
buy_final = buy
sell_final = sell
print(" Input: %s" % str(prices))
print("Output: %d" % (sell_final-buy_final))
The results:
$ /tmp/stock.py 7,1,5,3,6,4
Input: [7, 1, 5, 3, 6, 4]
Output: 5
$ /tmp/stock.py 1,2,4
Input: [1, 2, 4]
Output: 3
$ /tmp/stock.py 3,6,1,2
Input: [3, 6, 1, 2]
Output: 3
Let me know if you need more clarification, or if my assumptions are wrong