122. Best Time to Buy and Sell Stock II\\714. Best Time to Buy and Sell Stock with Transaction Fee
阿新 • • 發佈:2018-11-19
- 122. Best Time to Buy and Sell Stock II
思路:極大值減去極小值,所以適合 貪心演算法,把nums[x+1]-nums[x]
加在一起,就得到所有極大值減去極小值之和,也就是最大利潤。
class Solution:
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
max_interest=0
for x in range(len( prices)-1):
temp=prices[x+1]-prices[x]
if temp>0:max_interest+=temp
return max_interest
- 714. Best Time to Buy and Sell Stock with Transaction Fee
【貪心演算法】這道題我是 比較迷的,但想到就是錢多錢少的問題,我就明白了。
# 714. Best Time to Buy and Sell Stock with Transaction Fee
#
class Solution :
def maxProfit(self, prices, fee):
"""
:type prices: List[int]
:type fee: int
:rtype: int
"""
profit=0
cur_profit=0
min_price=prices[0]
max_price=prices[0]
for x in range(len(prices)):
# 每次交易的 price 中,選一個最小的,最大的,直到交易條件出現
min_price=min(min_price,prices[x])
max_price=max(max_price, prices[x])
cur_profit=max(cur_profit,prices[i]-min_price-fee)
# 只要保證賣出的price,後面有個比它小 fee 的,就不會虧錢
# 因為前面這次交易扣了 fee, 那麼只要有個小fee 的,分2次
# 就不會比一次賺的少 如:【1,5,2,8】,【1,3,2,8】
if (max_price- prices[x] )>=fee:
profit+=cur_profit
cur_profit=0
min_price=prices[x]
max_price=prices[x]
return profit+cur_profit