- 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
【贪心算法】这道题我是 比较迷的,但想到就是钱多钱少的问题,我就明白了。
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)):
min_price=min(min_price,prices[x])
max_price=max(max_price, prices[x])
cur_profit=max(cur_profit,prices[i]-min_price-fee)
if (max_price- prices[x] )>=fee:
profit+=cur_profit
cur_profit=0
min_price=prices[x]
max_price=prices[x]
return profit+cur_profit