题目描述:
给定一个数组 prices
,它的第 i
个元素 prices[i]
表示一支给定股票第 i
天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0
。
分析:
1. 从数组中找到最小和最大的数据
2.最大的数据必须在prices[1:]的区间内,即最大的数据必须在最小的数后面,否则返回0
class Solution1:
def maxProfit1(self, prices: list[int]) -> int:
min, max, ans = prices[0], prices[0], 0
for x in prices[1:]:
if x < min:
min = x
max = x + ans
elif x > max:
max = x
ans = x - min
return ans
实例化测试1:
solution = Solution1()
prices = [7, 1, 5, 3, 7, 4]
result = solution.maxProfit1(prices)
print(result)
# 输出6
实例化测试2:
prices2 = [7,6,4,3,1]
print(solution.maxProfit1(prices2))
#输出 0
扩展
求数组中,任意两位数之差最大
"""
求数组中,任意两位数之差最大
"""
class Solution:
def maxProfit(self, prices: list[int]) -> int:
min, max, ans = prices[0], prices[0], 0
for x in prices[1:]:
if x < min:
min = x
ans = max - x
elif x > max:
max = x
ans = max - min
return ans
实例化测试:
solution = Solution()
prices = [7, 1, 8, 3, 6, 4]
result = solution.maxProfit(prices)
print(result)
# 输出:7