假设有一个数组,它的第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
我的第一想法,所有组合算一遍,取最大的值。
class Solution:
"""
@param prices: Given an integer array
@return: Maximum profit
"""
def maxProfit(self, prices):
# write your code here
m = 0
for i in range(len(prices) - 1):
for j in range(i + 1, len(prices)):
n = prices[j] - prices[i]
m = max(m,n)
return m
———————————————————————————————————————————————————————— 分割线
a = Solution
prices = [1,3,5,2,4,6]
print(a.maxProfit(a, prices))
结果:
5
测试时时间复杂度过不去。在网上查找此问题,用动态规划解题。
class Solution:
"""
@param prices: Given an integer array
@return: Maximum profit
"""
def maxProfit(self, prices):
# write your code here
maxprofit = 0
minprise = prices[0]
for i in range(1,len(prices)):
maxprofit = max(maxprofit, prices[i] - minprise)
minprise = min(minprise, prices[i])
return maxprofit
——————————————————————————————————————————————————————————————
a = Solution
prices = [1,3,5,2,4,6]
print(a.maxProfit(a, prices))
结果:
5
成功通过。分析:
假设数列只有2个数[1,3],那么必然是1买入,3卖出。利润为3-1=2.
再增加一天,股票价格为5。那么买入价就是1与3做比较,1比较小,1买入。最大受益就是之前卖出的最大受益与今天卖出的受益作比较。
i = 1
maxprofit = max(0,3-1) = 2
minprice = min(1,3) = 1
i = 2
maxprofit = max(2,5-1) = 4
minprice = min(1,5) = 1
i = 3
……