leetcode-121-Best Time to Buy and Sell Stock

本文介绍了一种寻找股票买卖最佳时机以获得最大利润的算法。通过一次遍历数组,不断更新最低价格和最大利润,实现了高效求解。该算法适用于只允许进行一次买卖的情况。

题目描述:

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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 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
Explanation: In this case, no transaction is done, i.e. max profit = 0.

 

要完成的函数:

int maxProfit(vector<int> &prices)

 

说明:

1、给定一个vector,第几个元素表示某只股票第几天的价格,你只能买卖一次,要求输出最大的盈利额,你只能先买再卖。

2、这道题目其实是找出最大的差值,最暴力的解法无非是双重循环,外重循环找到每次“低峰值”,内重循环在“低峰值”之后计算差值,存储最大的差值。

但是上述做法你会发现没有必要找到每一个低峰值,因为第二次低峰值如果大于第一次低峰值,那么就没有必要做下去了;如果小于第一次低峰值,那么前面的内重循环到第二次低峰值就该停下来了。

我们需要的只是比第一个低峰值更小的另一个低峰值。

所以这道题目我们其实可以只用一次遍历就实现出来,不断更新低峰值,不断更新最大差值。

代码如下:

    int maxProfit(vector<int> &prices) 
    {
        int res=0;
        int minprice=INT_MAX;
        for(int i=0;i<prices.size();i++)
        {
            minprice= min(minprice, prices[i]);//不断更新低峰值
            res=max(res,prices[i]-minprice);//不断更新最大差值
        }
        return res;
    }

上述代码实测8ms,beats 80.63% of cpp submissions。

转载于:https://www.cnblogs.com/chenjx85/p/9104432.html

### LeetCode 121 题目解析 LeetCode121 题名为 **Best Time to Buy and Sell Stock**,其目标是在给定的价格数组中找到最大利润。可以通过一次交易(买入和卖出)来最大化收益。 #### 动态规划解法分析 对于该问题,可以采用动态规划的方法解决。以下是详细的解释: 定义状态变量 `T_i` 表示到第 `i` 天为止的最大利润。为了计算这个值,我们需要维护两个关键的状态: - 当前最低价格 `min_price`:表示在当前天之前股票的最低购买价格。 - 利润更新逻辑:每天尝试更新最大利润为当天价格减去之前的最低价格。 具体实现如下所示[^4]: ```cpp class Solution { public: int maxProfit(vector<int>& prices) { if (prices.empty()) return 0; int minPrice = INT_MAX; // 初始化最小价格为正无穷大 int maxProfit = 0; // 初始化最大利润为零 for (const auto& price : prices) { minPrice = std::min(minPrice, price); // 更新最低价格 maxProfit = std::max(maxProfit, price - minPrice); // 计算并更新最大利润 } return maxProfit; } }; ``` 上述代码的核心在于通过单次遍历完成所有操作,时间复杂度为 \(O(n)\),空间复杂度为 \(O(1)\)[^4]。 --- #### 关键点说明 1. 使用动态规划的思想时,虽然表面上看起来是一个贪心算法的应用场景,但实际上它也可以被看作是一种简化版的动态规划方法。这里的关键是利用了历史数据中的最优点(即最低价),从而减少了不必要的重复计算[^5]。 2. 对于更复杂的买卖次数限制情况(如最多两次交易等问题),则需要用到多维 DP 数组或者额外的状态变量来进行建模[^3]。 --- ### 总结 针对 LeetCode121 题的最佳解决方案之一就是基于动态规划思想设计出的时间效率高的线性扫描算法。这种方法不仅简单易懂而且性能优越,在实际应用中有很高的价值[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值