Python Challenge - Maximize Stock Trading Profit

This community-built FAQ covers the “Maximize Stock Trading Profit” code challenge in Python. You can find that challenge here, or pick any challenge you like from our list.

Top Discussions on the Python challenge Maximize Stock Trading Profit

There are currently no frequently asked questions or top answers associated with this challenge – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this challenge. Ask a question or post a solution by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this challenge, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in #get-help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to #get-help and #community:tips-and-resources. If you are wanting feedback or inspiration for a project, check out #project.

Looking for motivation to keep learning? Join our wider discussions in #community

Learn more about how to use this guide.

Found a bug? Report it online, or post in #community:Codecademy-Bug-Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

def max_profit_days(stock_prices): max_profit_amt = 0 max_day_1 = 0 max_day_2 = 1 for day in stock_prices: i = stock_prices.index(day) while i < len(stock_prices): if stock_prices[i] - day > max_profit_amt and i != stock_prices.index(day): max_day_1 = stock_prices.index(day) max_day_2 = i max_profit_amt = stock_prices[i] - day i+=1 return max_day_1, max_day_2
def max_profit_days(stock_prices): # Write your code here: max_profit = None for i in range(len(stock_prices)): for j in range(i + 1, len(stock_prices)): profit = stock_prices[j] - stock_prices[i] if max_profit is None or profit > max_profit: max_profit = profit buy_day, sell_day = i, j return (buy_day, sell_day) print(max_profit_days([17, 11, 60, 25, 150, 75, 31, 120]))

def max_profit_days(stock_prices):

Write your code here:

high = -999999
final = [0,0]

for i in range(len(stock_prices)):

for j in range(i + 1,len(stock_prices)):
  if stock_prices[j] - stock_prices[i] >= high:
    high = stock_prices[j] - stock_prices[i]
    final = (i,j)
    print(final)

  else:
    continue

return final

print(max_profit_days([17, 11, 60, 25, 150, 75, 31, 120]))

I made a helper function to find the index of the maximum (only using the part of the list from a specified index forward),
and I used that in a loop to get the max possible profit for buying on any given day,
and then finding the maximum out of all of those.

my code
def index_of_max(arr, starting_index = 0, ending_index = None):
    length = len(arr)
    if length < 1:
      return None
    if ending_index is None:
      ending_index = length - 1
    else:
      length = ending_index + 1
    max_so_far = arr[starting_index]
    max_index = starting_index
    for i in range(starting_index, length):
      if arr[i] > max_so_far:
        max_so_far = arr[i]
        max_index = i
    return max_index


def max_profit_days(stock_prices):

  length = len(stock_prices)
  profits = []
  sell_days = []

  for i in range(length - 1):
    # index i is the day that buy the stock
    differences = [(x - stock_prices[i]) for x in stock_prices]
    best_day = index_of_max(differences, starting_index = i + 1)
    profit = differences[best_day]
    profits.append(profit)
    sell_days.append(best_day)
    #print((i, best_day), profit)
  
  selected_index = index_of_max(profits)
  return (selected_index, sell_days[selected_index])

def max_profit_days(days):
highest_profit=None
b_day=None
s_day=None
days=list(days)
length=len(days)
for buy_day in days:
bday_index=days.index(buy_day)+1
for sell_day_index in range(bday_index,length):
sell_day=days[sell_day_index]
profit=sell_day-buy_day
if highest_profit==None or highest_profit<profit:
highest_profit=profit
b_day=days.index(buy_day)
s_day=days.index(sell_day)
return (b_day,s_day)

print(max_profit_days([17, 11, 60, 25, 150, 75, 31, 120]))

A O(n) solution:

def max_profit_days(stock_prices): # Write your code here: cur_min = stock_prices[0] max_prof = stock_prices[1] - stock_prices[0] buy_idx, sell_idx = 0, 1 min_idx = 0 for i in range(1, len(stock_prices)): if stock_prices[i] - stock_prices[min_idx] > max_prof: max_prof = stock_prices[i] - stock_prices[min_idx] sell_idx = i buy_idx = min_idx if stock_prices[i] < cur_min: min_idx = i cur_min = stock_prices[i] return buy_idx, sell_idx print(max_profit_days([7,5,5,4]))
def max_profit_days(stock_prices): # Write your code here: from itertools import permutations from numpy import Inf max_ret = -Inf ret = 0 for open,close in list(permutations(stock_prices,2)): i_open = stock_prices.index(open) i_close = stock_prices.index(close) if i_close > i_open: if close-open > max_ret: max_ret = close-open ret = (i_open,i_close) return ret
def max_profit_days(stock_prices): buy_day = 0 #initializing buy day at day 0 sell_day = 1 #initializing buy day at day 1 as it is the first day we can make profit with our stock stock_roi = (stock_prices[1] - stock_prices[0]) #stock_roi stores the highest roi we can make while iterating over the stock data for i in range(len(stock_prices)): #iterating over every possible buying day for j in range(i + 1, len(stock_prices)): #iterating over every possible selling day for a corresponding i if stock_prices[j] - stock_prices[i] > stock_roi: #if new found roi between days i and j outperformes old stock_roi... stock_roi = stock_prices[j] - stock_prices[i] #...it becomes the new stock_roi buy_day = i #for the latest stock_roi which is also the maximum buy_day stores days i... sell_day = j #...and j return buy_day, sell_day #so it can return them to the console print(max_profit_days([17, 11, 60, 25, 150, 75, 31, 120]))
def max_profit_days(stock_prices): indices = [] for i in range(1,len(stock_prices)): max_index = stock_prices.index(max(stock_prices[i:])) min_index = stock_prices.index(min(stock_prices[:max_index])) if [min_index,max_index] not in indices: indices.append([min_index,max_index]) differences = [stock_prices[max_index] - stock_prices[min_index] for min_index,max_index in indices] pairs = dict(zip(differences,indices)) return tuple(pairs.get(max(pairs.keys()))) print(max_profit_days([17, 11, 60, 25, 150, 75, 31, 1]))

If you’re stuck on a test case, remember that losses count too, you HAVE to buy the stock. took me a while to realize why i failed a test case.

def max_profit_days(stock_prices): maximum = -999999999999999999999999 z =() for i in range(0, len(stock_prices)): for j in range(i+1, len(stock_prices)): a = stock_prices[j] - stock_prices[i] if a > maximum: maximum = a z = (i,j) if len(z) == 0: return None return z print(max_profit_days([1,9]))
def max_profit_days(stock_prices): # Write your code here: best_profit = 1 best_buy = 0 best_pick = 0 for idx_stock in range(1,len(stock_prices)): if stock_prices[idx_stock] - stock_prices[best_pick] > stock_prices[best_profit] - stock_prices[best_buy]: best_profit = idx_stock best_buy = best_pick if stock_prices[idx_stock]<stock_prices[best_pick]: best_pick = idx_stock return (best_buy,best_profit) print(max_profit_days([17, 11, 60, 25, 150, 75, 31, 120]))
def max_profit_days(stock_prices): profit = -999999999 result = tuple() for i in range(len(stock_prices)): for j in range(i + 1, len(stock_prices)): current_profit = stock_prices[j] - stock_prices[i] if current_profit > profit: profit = current_profit result = (i,j) return result print(max_profit_days([17, 11, 60, 25, 150, 75, 31, 120]))
def max_profit_days(stock_prices): hold = [0,0,0] for x in range(0, len(stock_prices)): for y in range(x, len(stock_prices)): if stock_prices[y] - stock_prices[x] > hold[2]: hold[0], hold[1], hold[2] = x, y, stock_prices[y]-stock_prices[x] if hold[0] == hold[1]: hold[1] += 1 return hold[0], hold[1] print(max_profit_days([17, 11, 60, 25, 150, 75, 31, 120]))
def max_profit_days(stock_prices): # Write your code here: best_buy = 0 min_buy = stock_prices[0] min_buy_day = 0 best_sell = 1 best_profit = stock_prices[best_sell] - min_buy for day in range(1, len(stock_prices)): price = stock_prices[day] if price < min_buy: min_buy = price min_buy_day = day else: profit = price - min_buy if profit > best_profit: best_profit = profit best_sell = day best_buy = min_buy_day return best_buy, best_sell print(max_profit_days([17, 11, 60, 25, 150, 75, 31, 120]))

This was my solution:

def max_profit_days(stock_prices): # Write your code here: pos = 0 max_result = 0 first_test = True for price in stock_prices: if pos == len(stock_prices) - 1: break entry = stock_prices[pos] entry_bar = pos exit = max(stock_prices[entry_bar+1:]) result = exit - entry if max_result < result or first_test: first_test = False max_result = result exit_bar = stock_prices.index(exit) trade = (entry_bar, exit_bar) pos += 1 return trade print(max_profit_days([17, 11, 60, 25, 150, 75, 31, 120]))