返回
每日一道算法题031 买卖股票的最佳时机
Android
2024-01-05 01:56:03
### 引言
在股票市场中,投资者往往会面临一个问题:在某个时间段内,如何买入和卖出股票才能获得最大的利润?这正是算法题「买卖股票的最佳时机」所要解决的问题。
### 问题
给定一个数组 prices,其中 prices[i] 是股票在第 i 天的价格。
prices = [7, 1, 5, 3, 6, 4]
### 算法解法
我们介绍两种解法来解决该算法题:
#### 单循环解法
第一种解法使用单循环,当前第 n 项减去前 n-1 项的最小值,就是前 n 项的最大利润。具体步骤如下:
1. 初始化变量 min_price 和 max_profit 分别为正无穷大和 0。
2. 遍历数组 prices,对于每个元素 prices[i]:
- 更新 min_price 为 min(min_price, prices[i])。
- 更新 max_profit 为 max(max_profit, prices[i] - min_price)。
3. 返回 max_profit。
```python
def max_profit(prices):
min_price = float('inf')
max_profit = 0
for price in prices:
min_price = min(min_price, price)
max_profit = max(max_profit, price - min_price)
return max_profit
prices = [7, 1, 5, 3, 6, 4]
print(max_profit(prices))
输出结果:
5
定义两个值
第二种解法定义两个值分别用于记录前 n 项的最小值与最大利润。具体步骤如下:
- 初始化变量 min_price 和 max_profit 分别为正无穷大和 0。
- 遍历数组 prices,对于每个元素 prices[i]:
- 如果 prices[i] < min_price,则更新 min_price 为 prices[i]。
- 如果 prices[i] - min_price > max_profit,则更新 max_profit 为 prices[i] - min_price。
- 返回 max_profit。
def max_profit(prices):
min_price = float('inf')
max_profit = 0
for price in prices:
if price < min_price:
min_price = price
elif price - min_price > max_profit:
max_profit = price - min_price
return max_profit
prices = [7, 1, 5, 3, 6, 4]
print(max_profit(prices))
输出结果:
5
总结
在这篇文章中,我们介绍了「买卖股票的最佳时机」算法题的两种解法。第一种解法使用单循环,第二种解法定义两个值分别用于记录前 n 项的最小值与最大利润。这两种解法都是有效的,大家可以根据自己的喜好选择适合自己的解法。