【LeetCode】121. Best Time to Buy and Sell Stock

本文介绍了一种用于计算股票买卖最大收益的算法,并给出了优化前后的实现代码对比。通过避免使用双重循环,将时间复杂度从O(n^2)降低到O(n),确保了算法在大规模数据集上的高效运行。

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

问题描述

股票交易。数组第i个元素表示第i天股票的价格,整个过程只能买一次和卖一次,设计一个算法寻找最大收益。

例1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
只能先买进才能卖出,所以最大收益为6-1=5,而不是7-1=6。

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


贪心。其实就是找一个数组里面的最大差值j-i,保证i < j即可。

//但是这个方法两重循环,超时了!
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.size() == 0) return 0;
        int result=0;
        int temp=0;
        for(int i=0;i<prices.size()-1;i++){
            for(int j=i+1;j<prices.size();j++){
                temp=prices[j]-prices[i];
                result=max(result,temp);
            }
        }
        return result;
    }
};

Time Limit Exceeded:
Last executed input:
[10000,9999,9998,9997,9996,9995,9994,9993,9992,9991,9990,9989…….]

所以我们需要优化。
AC代码如下:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int result=0;   //始终记录最大值
        int temp=0;     //记录当天的收益,若为负,则置0重新计算收益(此时最大值已经被result保存下来了)
        for(int i=1; i<prices.size(); i++){
           temp += (prices[i]-prices[i-1]);
           if(temp<0){
               temp=0;
           }
           result=max(result,temp);
        }
        return result;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值