algorithm notes: leetcode#122 best time to buy and sell stock 2

Problem


Solution


Analysis

Python implementation

1
2
3
4
5
6
7
class (object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
return sum([prices[i+1]-prices[i] for i in range(len(prices)-1) if prices[i+1]>prices[i]])

Java implementation

1
2
3
4
5
6
7
8
9
class {
public int maxProfit(int[] prices) {
int sum = 0;
for(int i = 1; i < prices.length; i++)
if(prices[i] > prices[i-1])
sum += prices[i] - prices[i-1];
return sum;
}
}

Time complexity

O(n).

Space complexity

O(1).


122. Best Time to Buy and Sell Stock II
(中文版) 算法笔记: 力扣#122 买卖股票的最佳时机 II