题目:
给定一个数组,第i个位置表示第i天的价格,要求只能完成一组交易(买入一次+卖出一次),求出最大利润。
解题思路:
对数组进行遍历,保存当前的最小买入价格和当前的最大利润,遍历结束后,返回最终的最大利润即可。
代码(python):
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
n = len(prices)
if n==0 or n==1:
return 0
min0 = prices[0]
max0 = 0
for i in range(n):
if prices[i]<min0:
min0 = prices[i]
continue
if prices[i]>=min0:
if prices[i]-min0>max0:
max0 = prices[i]-min0
continue
else:
continue
return max0
本文介绍了一种通过遍历价格数组来寻找股票买卖最佳时机的方法,以实现最大利润。算法维护了一个当前最低买入价格和最大可能利润,在遍历过程中不断更新这两个变量。
Python&spm=1001.2101.3001.5002&articleId=78615442&d=1&t=3&u=e3e4a09df6394eb68fd86c7707d6bb3a)
2462

被折叠的 条评论
为什么被折叠?



