算法笔记: 力扣#121 买卖股票的最佳时机

问题描述


解法


分析

Python 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class :
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 实现

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;
}
}

时间复杂度

O(n).

空间复杂度

O(1).

链接


121. Best Time to Buy and Sell Stock
121. 买卖股票的最佳时机
(English version) Algorithm Notes: Leetcode#121 Best Time to Buy and Sell Stock