Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Example 1:
Input: [7, 1, 5, 3, 6, 4] Output: 5 max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1] Output: 0 In this case, no transaction is done, i.e. max profit = 0.题目的意思就是你先买后卖,所以不是简单最大值最小值相差,因为最大值不能在第一位。
class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
if None==prices or len(prices)<2:
return 0
min=prices[0]
# print len(prices)
max_diff=0
for i in range(1,len(prices)):
if prices[i-1]<min: #因为一定买的比卖的贵
min=prices[i-1]
print min
# print i
# print prices[i-1]
cur_diff=prices[i-1]-min
if cur_diff>max_diff:
max_diff = cur_diff
return max_diff
prices=[82,2,44,1,1,3,2,7,4,5,7,6]
print Solution().maxProfit(prices)
本文介绍了一种算法,用于计算给定股票价格序列中能够获得的最大利润。该算法假设只能进行一次买入和卖出操作,并确保卖出价格高于买入价格。通过遍历价格序列找到最低买入点和最高利润。
469

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



