LeetCode——Best Time to Buy and Sell Stock

本文介绍了一个经典的算法问题:如何从给定的股票价格数组中找到最佳买卖时机以获得最大利润。通过一次遍历并记录最小购买价格及最大利润的方式解决此问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode——Best Time to Buy and Sell Stock

# 121

Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example 1:

Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

Example 2:

Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

这一题的目的是求数组中,找出两个相差最大的元素,必须是后一个元素减去前一个元素。这一题明显是动态规划。当然可以用暴力破解,时间复杂度为O(n2)。 暴力破解法就不写了。
有一种简单的思想就是,就是使用一次遍历,记录遍历过程中的最小元素,并将当前值与当前遍历的最小元素的差记录为最大利润。遍历结束后,即能得到最大利润。

  • C++
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int res = 0, buy = INT_MAX;
        for (int price : prices) {
            buy = min(buy, price);
            res = max(res, price - buy);
        }
        return res;
    }
};

动态规划的方法,其实思想是和前面做过的一题Maximum Subarray 很相似。就是要用两个变量分别维护局部最优全局最优

  • C++
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.size() == 0)
            return 0;
        int local = 0;
        int global = 0;
        for(int i = 0;i < prices.size() - 1;i++) {
            local = max(local + prices[i + 1] - prices[i],0);
            global = max(local,global);
        }
        return global;
    }
};

这里的动态规划思想和Maximum Subarray的思想是一样的,设置两个变量,维护局部最优和全局最优。

  • Python
class Solution:
    def maxProfit(self, prices):
        """
        :type prices: List[int]
        :rtype: int
        """
        if len(prices) <= 1: return 0
        low = prices[0]
        maxprofit = 0
        for i in range(len(prices)):
            if prices[i] < low: low = prices[i]
            maxprofit = max(maxprofit, prices[i] - low)
        return maxprofit
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值