【Leetcode】122. Best Time to Buy and Sell Stock II

【Leetcode】122. Best Time to Buy and Sell Stock II_第1张图片

This problem is aim to find every increasing subsequence in list, and sum all the difference between the head and the tail of subsequence.


【Leetcode】122. Best Time to Buy and Sell Stock II_第2张图片

1 对于[1,2,3,4,5]的情况,按照code是prices[1] - prices[0] + prices[2] - prices[1] + prices[3] - prices[2] + prices[4] - prices[3],最后很多中间项是抵消了的,最终就是prices[4] - prices[0] 


【Leetcode】122. Best Time to Buy and Sell Stock II_第3张图片

我这里还多设置一个变量lowPrice,其实没有必要设,只需要每次比较当前price和previous price就好了,大于就有profit,小于就没有


【Leetcode】122. Best Time to Buy and Sell Stock II_第4张图片

要注意这种特殊情况


【Leetcode】122. Best Time to Buy and Sell Stock II_第5张图片

你可能感兴趣的:(【Leetcode】122. Best Time to Buy and Sell Stock II)