149. Best Time to Buy and Sell Stock
Description
假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。
Example 1
Input: [3, 2, 3, 1, 2]
Output: 1
Explanation: You can buy at the third day and then sell it at the 4th day. The profit is 2 - 1 = 1
分析:显然,由于买卖次数只有一次,故我们希望找到一个差最大的值,即尽可能地使买入的时候价钱低,卖出的时候价钱高。 我们可以在遍历过程中运用变量before_min_num存储已遍历的情况下的最小值,比较之前的差与当前位置所能取得的最优的差相比,如果当前更优则更新,否则继续。
class Solution:
"""
@param prices: Given an integer array
@return: Maximum profit
"""
def maxProfit(self, prices):
# write your code here
res=0
before_min_num=10000000 #初始化为一个极大值
for each in prices:
before_min_num=min(before_min_num,each)
res=max(res,each-before_min_num)
return res
本文详细解析了如何设计算法寻找股票买卖的最佳时机以获取最大利润。通过实例输入[3,2,3,1,2],阐述了算法的运行过程及结果。关键在于寻找价格差的最大值,确保买入价低,卖出价高。
998

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



