想到: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]))