Leetcode121. 买卖股票的最佳时机

本文探讨了两解法解决LeetCode题目121买卖股票的最佳时机:暴力搜索的O(n^2)方法和贪心算法的一次遍历。通过实例展示了两种方法的优劣,并聚焦于高效算法的实现与优化。

Every day a leetcode

题目来源:121. 买卖股票的最佳时机

解法1:暴力

代码:

int max(int a,int b)
{
    return a>b?a:b;
}
int maxProfit(int* prices, int pricesSize){
    int maxProfit=0;
    int n=pricesSize;
    for(int i=0;i<n-1;i++)
    {
        for(int j=i+1;j<n;j++)
        {
            maxProfit=max((prices[j]-prices[i]),maxProfit);
        }
    }
    if(maxProfit>0) return maxProfit;
    else return 0;
}

结果:
在这里插入图片描述

解法2:贪心

一次遍历,更新最低股票价格和最大利润。

代码:

int maxProfit(int* prices, int pricesSize){
    int maxProfit=0;
    int minPrice=prices[0];
    int n=pricesSize;
    for(int i=0;i<n;i++)
    {
        if(prices[i]<minPrice) minPrice=prices[i];
        if(prices[i]-minPrice>maxProfit) maxProfit=prices[i]-minPrice;
    }
    return maxProfit;
}

结果:
在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

UestcXiye

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

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

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

打赏作者

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

抵扣说明:

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

余额充值