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

Problem


Solution


Analysis

Python implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class (object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
max_profit = 0
buy = float('Inf')
for price in prices:
if price < buy:
buy = price
if price - buy > max_profit:
max_profit = price - buy
return max_profit

Java implementation

1
2
3
4
5
6
7
8
9
10
11
class {
public int maxProfit(int[] prices) {
int maxProfit = 0;
int buy = Integer.MAX_VALUE;
for(int price : prices){
if(price < buy){ buy = price; }
if(price - buy > maxProfit){ maxProfit = price - buy;}
}
return maxProfit;
}
}

Time complexity

O(n).

Space complexity

O(1).


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