《LeetCode刷题》—121. 买卖股票的最佳时机

《LeetCode刷题》—121. 买卖股票的最佳时机

一、题目内容

原题连接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/

题目:

在这里插入图片描述

二、个人答案(Java)

注意:该题个人答案未通过,运行时间超时

思路:相当于给一段数组,后面一个数减去前面一个数,求最大值,马上就想到了反向循环,循环两次,外循环每一个元素,内循环去循环前面的每一个数,求其最大值

代码:

class Solution {
    public int maxProfit(int[] prices) {
        int Max=0;
        for (int i = prices.length-1; i >=0; i--) {
            for (int j = i-1; j >=0 ; j--) {
                int temp=prices[i]-prices[j];
                if (temp>Max){
                    Max=temp;
                }
            }
        }
        return Max;
    }
}
三、官方答案(Java)
方法一:暴力法

代码

public class Solution {
    public int maxProfit(int[] prices) {
        int maxprofit = 0;
        for (int i = 0; i < prices.length - 1; i++) {
            for (int j = i + 1; j < prices.length; j++) {
                int profit = prices[j] - prices[i];
                if (profit > maxprofit) {
                    maxprofit = profit;
                }
            }
        }
        return maxprofit;
    }
}
方法二:一次遍历

思路:

在这里插入图片描述

代码

public class Solution {
    public int maxProfit(int prices[]) {
        int minprice = Integer.MAX_VALUE;
        int maxprofit = 0;
        for (int i = 0; i < prices.length; i++) {
            if (prices[i] < minprice) {
                minprice = prices[i];
            } else if (prices[i] - minprice > maxprofit) {
                maxprofit = prices[i] - minprice;
            }
        }
        return maxprofit;
    }
}

官方答案来源:

作者:LeetCode-Solution
链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/solution/121-mai-mai-gu-piao-de-zui-jia-shi-ji-by-leetcode-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

金士曼

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

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

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

打赏作者

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

抵扣说明:

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

余额充值