版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/welcom_/article/details/84102129
- 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