【力扣 - 买卖股票的最佳时机】

题目描述

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。

你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
在这里插入图片描述

题解

int maxProfit(int* prices, int pricesSize) {
    if (pricesSize < 2) {
        return 0; // If there are less than 2 prices, profit is 0
    }
    
    int min = prices[0];
    int max = prices[0];
    int maxProfit = 0;

    for (int i = 1; i < pricesSize; i++) {
        if (prices[i] < min) {
            min = prices[i];
            max = prices[i]; // Reset max when updating min
        } else if (prices[i] > max) {
            max = prices[i];
            maxProfit = fmax(maxProfit, max - min); // Update maxProfit if a better profit is found
        }
    }

    return maxProfit;
}
### 解题思路 LeetCode 122 题要求通过股票交易获得最大利润,允许进行多次交易(即在买入并卖出股票后,可以再次买入并卖出)。问题的核心在于如何选择买入和卖出的时机,以最大化总利润。 #### 贪心算法 贪心算法是解决该问题的高效方法。其核心思想是:只要第二天的价格高于今天,就进行交易,将差值计入总利润。这样可以保证每次交易都获得正收益,最终实现全局利润的最大化[^4]。 这种方法的时间复杂度为 $O(n)$,其中 $n$ 是价格数组的长度。空间复杂度为 $O(1)$,因为只需要常数级别的额外空间。 #### 示例说明 以 `prices = [7,1,5,3,6,4]` 为例: - 在第 2 天买入(价格为 1),第 3 天卖出(价格为 5),利润为 4。 - 在第 4 天买入(价格为 3),第 5 天卖出(价格为 6),利润为 3。 - 总利润为 7。 通过贪心策略,可以在每一天比较是否值得买入或卖出,从而逐步累积最大利润[^2]。 ### 代码实现 以下是基于贪心算法的实现: ```cpp class Solution { public: int maxProfit(vector<int>& prices) { int ans = 0; for (int i = 0; i < prices.size() - 1; ++i) { // 如果第二天价格高于当天,则交易 if (prices[i + 1] > prices[i]) { ans += prices[i + 1] - prices[i]; } } return ans; } }; ``` ### 改进版实现 另一种改进版本使用了更复杂的逻辑来处理买入和卖出的状态管理,适用于某些特殊情况下的优化需求: ```c int maxProfit(int* prices, int pricesSize) { int buy = -1, sell = 0, sum = 0, i = 0; while (i < pricesSize) { if (buy == -1) { if (i + 1 < pricesSize && prices[i] < prices[i + 1]) { buy = prices[i]; sell = prices[i + 1]; } } else { if (i + 1 >= pricesSize || prices[i] > prices[i + 1]) { sum += sell - buy; buy = -1; } else { sell = prices[i + 1]; } } i++; } return sum; } ``` 该实现通过状态变量 `buy` 和 `sell` 来跟踪当前是否持有股票,并根据价格趋势决定是否继续持有或卖出[^3]。 ### 算法特点 - **时间效率**:由于仅遍历一次价格数组,时间复杂度为线性级别。 - **空间效率**:不需要额外存储数据结构,空间复杂度为常数级别。 - **适用场景**:适用于允许多次交易且不禁止连续买卖的情况。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

六月悉茗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值