121. Best Time to Buy and Sell Stock
problem
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.
给出n天的价格,N天内先买后卖(允许一次),求最大盈利
一定要先买后卖,所以想法2,3不能随便取最大最小值
solution
- 想法
嵌套遍历,每个差值都求出来- 最小值--之后最大值
- 转化为两两差值的list,求list和最大最小差值
- 不用嵌套,遍历的次序刚好满足先买后卖的条件,(不用嵌套后再根据条件过滤)
即每一天,都对最小值,最大值做一个判断
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
maxdiff = 0
min = 2**63 - 1
for i in prices:
if i < min:
min = i
diff = i - min
if maxdiff < diff:
maxdiff = diff
return maxdiff

浙公网安备 33010602011771号