题目链接
https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/
题目描述
代码初步
- 方法1: 峰谷法
参考leetcode官方给出的思路 - 算法
假设给定的数组为:
[7, 1, 5, 3, 6, 4]
如果我们在图表上绘制给定数组中的数字,我们将会得到:
我们的兴趣点落在连续的峰和谷上。关键是我们需要考虑到紧跟谷的每一个峰值以最大化利润。如果我们试图跳过其中一个峰值来获取更多利润,那么我们最终将失去其中一笔交易中获得的利润,从而导致总利润的降低。因为C的长度是不可能大于A+B的
代码欣赏
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
maxprofit = 0
if len(prices)<1:
return maxprofit
valley=prices[0]
i=1
peak=prices[0]
while i<len(prices):
# 查找谷底的值:谷底的特征就是后一个数B大于前一个数A,则A为谷底
while i<len(prices) and (prices[i]<=prices[i-1]):
i=i+1
valley = prices[i-1]
# 查找谷峰的值:谷峰的特征就是后一个数B小于前一个数A,则A为谷底
while i<len(prices) and (prices[i]>=prices[i-1]):
i=i+1
peak = prices[i-1]
maxprofit += peak-valley
return maxprofit