题目:
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.
题意:
数组第i个数是股票第i天的价格,求出先买进一只股票,再卖出这只股票的最大收益
代码:
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
length = len(prices)
if length == 0 :
return 0
else :
result = 0
min_lis = list()
max_lis = list()
result = list()
min_lis.append(prices[0])
temp = list()
temp = prices[::-1]
max_lis.append(temp[0])
for i in range(1,length) :
if prices[i] < min_lis[i-1] :
min_lis.append(prices[i])
else :
min_lis.append(min_lis[i-1])
for i in range(1,length) :
if temp[i] > max_lis[i-1] :
max_lis.append(temp[i])
else :
max_lis.append(max_lis[i-1])
max_lis = max_lis[::-1]
for i in range(length) :
result.append(max_lis[i] - min_lis[i])
return max(result)
笔记:
range函数倒数遍历时的表示:
range(length,0,-1) :从length遍历到0,每隔一个遍历一次