给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
暴力解法
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
ans = 0
for i in range(len(prices)):
for j in range(i + 1, len(prices)):
ans = max(ans, prices[j] - prices[i])
return ans
贪心算法
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
# ans = 0
# for i in range(len(prices)):
# for j in range(i + 1, len(prices)):
# ans = max(ans, prices[j] - prices[i])
# return ans
minprice = int(1e9)
n = len(prices)
maxProfit = 0
for price in prices:
maxProfit = max(price - minprice, maxProfit)
minprice = min(minprice, price)
return maxProfit
显然,如果我们真的在买卖股票,我们肯定会想:如果我是在历史最低点买的股票就好了!太好了,在题目中,我们只要用一个变量记录一个历史最低价格 minprice,我们就可以假设自己的股票是在那天买的。那么我们在第 i 天卖出股票能得到的利润就是 prices[i] - minprice。
我们只需要遍历价格数组一遍,记录历史最低点,然后在每一天考虑这么一个问题:如果我是在历史最低点买进的,那么我今天卖出能赚多少钱?当考虑完所有天数之时,我们就得到了最好的答案。
def test_maxProfit():
solution = Solution()
# Test Case 1
prices = [7, 1, 5, 3, 6, 4]
assert solution.maxProfit(prices) == 5
print("Test case passed.")
# Run the test
test_maxProfit()