假设我们可以将昨天的股票价格作为列表访问,其中:
指数是交易开盘时间的分钟数,即当地时间上午9:30。 这些值是当时Apple股票的美元价格。 因此,如果股票在上午10:30成本为500美元,则stock_prices_yesterday [60] = 500。
编写一个有效的函数,该函数需要stock_prices_yesterday并返回我昨天1次购买和1次销售1份Apple股票所能获得的最佳利润。
我提出的解决方案:
def get_best_stock_price(list):
first_minimum_value = min(list)
index_of_the_minimum_value = list.index(first_lowest_value)
new_list_excluding_all_the_unwanted_items = list[new_list_index:]
max_new = max(new_list)
return max_new - first_minimum_value
他们提供的解决方案:
def get_max_profit(stock_prices_yesterday):
if len(stock_prices_yesterday) < 2:
raise ValueError('Getting a profit requires at least 2 prices')
min_price = stock_prices_yesterday[0]
max_profit = stock_prices_yesterday[1] - stock_prices_yesterday[0]
for current_time in xrange(1, len(stock_prices_yesterday)):
current_price = stock_prices_yesterday[current_time]
potential_profit = current_price - min_price
max_profit = max(max_profit, potential_profit)
min_price = min(min_price, current_price)
return max_profit
我的回答是否足以满足他们的要求?如果不是我怎么能改善它。我的功能缺乏什么?
它们提供的功能包括O(n)时间和大O符号语言中的O(1)O(1)空间。
答案 0 :(得分:0)
首先,您的解决方案是错误的,但我们稍后会介绍原因。
从技术上讲,你的解决方案是O(n),但不是很好。
分别致电min
和max
,每项费用为n
次。查找项目的索引会花费另外〜n
次操作。您的运行时间实际上是3n
,因此在技术上受n
约束,但如果您在单个for循环中找到所有这三个内容,它可能会更有效。例如:
idx = 0
max = 0
min = 9999999
for i, item in enumerate(list):
if item > max:
max = item
if item < min:
min = item
idx = i
接下来,我不确定您的程序中有new_list_index
或new_list
,但除非对列表进行排序(这会使整个问题变得微不足道),否则您需要搜索整个列表找到最大值。
最后,因为您使用new_list_excluding_all_the_unwanted_items
存储输入列表的切片,所以空间复杂度受输入列表大小的约束,同时也为O(n)提供空间复杂度。
然而,他们的方法使用单个for循环,并且仅使用固定数量的变量,从而为它们提供O(n)时间和O(1)空间复杂度。
至于改进,我相信我可以比任何一种解决方案做得更好 。
def get_max_profit(list):
"""Use list[0] to store min
and list[1] to store max
"""
# Swap the first two if they are out of order
if list[0] > list[1]:
list[0], list[1] = list[1], list[0]
# Find min and max in remainder of list
for price in list[2:]:
if price < list[0]:
list[0] = price
if price > list[1]:
list[1] = price
# Return the difference
return list[1] - list[0]
我的解决方案是使用list[0]
存储min
值和list[1]
来存储max
值。我的解决方案仍然是O(n)时间和O(1)空间,但是完全就位,并且不需要任何额外的存储空间。
它也牺牲了可读性以获得可忽略的性能增益,因此永远不应该使用。