[算法和数据结构入门][Day7]打擂法实现买卖股票的最佳时机

DAY7:买卖股票的最佳时机
给定一个数组,它的第 i 个元素是这个股票第 i 天的价格。
你最多只允许完成一笔交易(即买入和卖出一支股票一次),设计一个算法来计算你所能获取的最大利润(不能在买入股票前卖出股票)
在这里插入图片描述

# 买入卖出单个打擂
def maxProfit(prices):  
    buy,sell = prices[0],0       
    for price in prices:
        buy = min(buy,price)
        sell = max(sell,price - buy)        
    return sell
print(maxProfit([7,1,5,3,6,4]))
print(maxProfit([7,6,4,3,1]))
发布了42 篇原创文章 · 获赞 28 · 访问量 4961

猜你喜欢

转载自blog.csdn.net/KaelCui/article/details/105547808