力扣122. 买卖股票的最佳时机 II
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
示例 1:
输入: [7,1,5,3,6,4]
输出: 7
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。
随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。示例 2:
输入: [7,6,4,3,1]
输出: 0
解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。
解题思路
确定通过交易能够获得的最大利润(交易次数没有限制),需要找出那些共同使得利润最大化的买入及卖出价格。
计算每天价格的差值temp,筛选使得temp>=0,则永不亏损,遍历整个数组,求和temp使之最大
一 、暴力求解/搜索法
就这道题来说暴力解法(“回溯搜索”、“回溯法)是比贪心算法难的,我自己写不出来
官方是重新定义一个函数来递进计算与所有可能的交易组合相对应的利润,并找出它们中的最大利润。比较难理解,有大佬将官方的递进函数拆解开写成if—else形式
附上大佬的“模拟游标,寻找买点”
class Solution:
def maxProfit(self, prices: List[int]) -> int:
x_cursor = 0
earn = 0
while x_cursor < len(prices):
x_val = prices[x_cursor]
y_cursor = x_cursor + 1
best_y_val = None
best_y_cursor = None
while y_cursor < len(prices):
# if y_cursor == x_cursor:
# break
y_val = prices[y_cursor]
if not best_y_val:
# 没有发现好的卖点
if x_val < y_val:
# 发现卖点
best_y_val = y_val
best_y_cursor = y_cursor
else:
# 没有卖点,当日不买,换一天
break
else:
# 有卖点,再找更好的卖点
if best_y_val < y_val:
best_y_val = y_val
best_y_cursor = y_cursor
else:
break
y_cursor = y_cursor + 1
if best_y_val:
earn = earn + best_y_val - x_val
x_cursor = best_y_cursor + 1
best_y_val = None
else:
x_cursor = x_cursor + 1
return earn
作者:li-yi-feng-3
链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/solution/python3bao-li-jie-fa-by-li-yi-feng-3/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
二、贪心算法/动态规划
参照最大子序和。
很多贪心算法和动态规划是一样的,只需要略微修改一下代码。
就我个人而言,从后往前的算法流程的逻辑更加通顺,等价于每天都买卖。
因为利润满足price=p(i)-p(j)=p(i)-p(i-1)+p(i-1)-p(i-2)+…+p(j+1)-p(j)
price>0表示盈利,price<=0表示不盈利,所有盈利累加就是最大盈利
及策略是所有上涨交易日都买卖(赚到所有利润)。
在此过程中每个数据只使用了一次或者没有使用,满足同一天只能进行一次操作的题意。
#python3 从后往前
class Solution:
def maxProfit(self, prices: List[int]) -> int:
maxprofit=0
for i in range(len(prices)-1,0,-1):
maxprofit+=prices[i]-prices[i-1] if prices[i]>prices[i-1] else 0
return maxprofit
#python3 从前往后
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
for i in range(1, len(prices)):
tmp = prices[i] - prices[i - 1]
if tmp > 0: profit += tmp
return profit