python 测试题 买卖股票的最佳时机
时间: 2025-06-19 11:40:08 浏览: 20
### Python 实现买卖股票最佳时机的测试题与练习题
以下是一些关于 Python 实现买卖股票最佳时机的测试题和练习题,涵盖了不同的交易限制条件。
#### 1. 最佳买卖股票一次
编写一个函数,计算在给定的股票价格列表中,最多可以获取的最大利润。假设只允许进行一次买入和一次卖出的操作。
```python
def maxProfit(prices):
if not prices:
return 0
min_price = prices[0]
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
```
测试用例:
```python
print(maxProfit([7, 1, 5, 3, 6, 4])) # 输出:5
print(maxProfit([7, 6, 4, 3, 1])) # 输出:0
```
#### 2. 最佳买卖股票多次
编写一个函数,计算在给定的股票价格列表中,最多可以获取的最大利润。允许多次买入和卖出的操作。
```python
def maxProfit(prices):
total_profit = 0
for i in range(1, len(prices)):
if prices[i] > prices[i - 1]:
total_profit += prices[i] - prices[i - 1] # 累加利润
return total_profit
```
测试用例:
```python
print(maxProfit([7, 1, 5, 3, 6, 4])) # 输出:7
print(maxProfit([1, 2, 3, 4, 5])) # 输出:4
```
#### 3. 带有冷却期的最佳买卖股票
编写一个函数,计算在给定的股票价格列表中,最多可以获取的最大利润。假设每次卖出后必须等待一天(即冷却期)才能再次购买。
```python
def maxProfit(prices):
if not prices:
return 0
n = len(prices)
dp = [[0, 0] for _ in range(n)]
dp[0][0] = 0
dp[0][1] = -prices[0]
for i in range(1, n):
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i]) # 不持有股票
dp[i][1] = max(dp[i - 1][1], dp[i - 2][0] - prices[i] if i > 1 else dp[i - 1][0] - prices[i]) # 持有股票
return dp[-1][0]
```
测试用例:
```python
print(maxProfit([1, 2, 3, 0, 2])) # 输出:3
```
#### 4. 最多两次交易的最佳买卖股票
编写一个函数,计算在给定的股票价格列表中,最多可以获取的最大利润。假设最多只能完成两笔交易。
```python
def maxProfit(prices):
if not prices:
return 0
n = len(prices)
left_profits = [0] * n
right_profits = [0] * n
min_price = prices[0]
for i in range(1, n):
min_price = min(min_price, prices[i])
left_profits[i] = max(left_profits[i - 1], prices[i] - min_price)
max_price = prices[-1]
for i in range(n - 2, -1, -1):
max_price = max(max_price, prices[i])
right_profits[i] = max(right_profits[i + 1], max_price - prices[i])
max_profit = 0
for i in range(n):
max_profit = max(max_profit, left_profits[i] + right_profits[i])
return max_profit
```
测试用例:
```python
print(maxProfit([3, 3, 5, 0, 0, 3, 1, 4])) # 输出:6
```
#### 5. 含有交易费用的最佳买卖股票
编写一个函数,计算在给定的股票价格列表中,最多可以获取的最大利润。假设每次交易都有固定的手续费。
```python
def maxProfit(prices, fee):
if not prices:
return 0
cash, hold = 0, -prices[0]
for price in prices[1:]:
cash = max(cash, hold + price - fee) # 卖出股票
hold = max(hold, cash - price) # 买入股票
return cash
```
测试用例:
```python
print(maxProfit([1, 3, 2, 8, 4, 9], 2)) # 输出:8
```
###
阅读全文
相关推荐



















