122. 买卖股票的最佳时机 II

 

 

 

 

 

 

 

 思路:

想到:prices中一列数字,任取一个为买入价格buy,在其右边任取一个为卖出价格sell;
取[buy,...,sell]区间中相邻数字之差,这些差值求和为sum,则必有sell-buy = sum;

本题中求最大收益,所以遍历prices,找到prices[i]-prices[i-1] > 0的位置作为买入点。
此后一直遍历到prices末尾,将相邻两个元素的差加到ans中,最后得ans即为最大利润。

代码一:
 1 class Solution(object):
 2     def maxProfit(self, prices):
 3         """
 4         :type prices: List[int]
 5         :rtype: int
 6         """
 7         i = 0
 8         ans = 0
 9         while i < len(prices) - 1:
10             if prices[i + 1] < prices[i]:
11                 i += 1
12                 continue
13             else:
14                 buy = prices[i]
15                 ans += prices[i + 1] - buy
16                 i += 1
17         return ans
18 
19 if __name__ == '__main__':
20     solution = Solution()
21     print(solution.maxProfit2([7, 1, 5, 3, 4, 6]))

代码二:

 1 class Solution(object):
 2     def maxProfit(self, prices):
 3         """
 4         :type prices: List[int]
 5         :rtype: int
 6         """
 7         ans = 0
 8         for i in range(1, len(prices)):
 9             if prices[i] > prices[i - 1]:
10                 ans += prices[i] - prices[i - 1]
11         return ans
12 
13 if __name__ == '__main__':
14     solution = Solution()
15     print(solution.maxProfit([7, 1, 5, 3, 4, 6]))

 

 
posted @ 2020-04-21 23:13  人间烟火地三鲜  阅读(167)  评论(0编辑  收藏  举报