3.18 leetcode 买卖股票的最佳时机 (数组:一次遍历,保存每次股票最低的点)

该博客介绍了如何使用一次遍历来解决LeetCode中的股票交易问题,通过记录每次遍历到的股票最低价格,计算与当前价格的差值,以找到最大收益。
摘要由CSDN通过智能技术生成

在这里插入图片描述

暴力法

class Solution {
    public int maxProfit(int[] prices) {
        int n = prices.length;
        int yin = 0;
        //int flag = 0;
        for(int i = 0; i < n-1; i++)
        {
            for(int j = i+1; j < n; j++)
            {
                //yin = Math.max(prices[j] - prices[i], yin);
              
                int cha = prices[j] - prices[i];
                if(cha > yin)
                    yin = cha;
                
            }
        }
        return yin;
    }
}

一次遍历:保存每次股票最低的点,往后计算与当前最低值的差值,保存差值最大的点

class Solution {
    public int maxProfit(int[] prices) {
        int minprice = Integer.MAX_VALUE;
        int cha = 0;
        for(int i = 0; i < prices.length; i++ )
        {
            if(prices[i] < minprice)
            {
                minprice = prices[i];
            }
            else
            {
                cha = Math.max(prices[i] - minprice, cha);
            }

        }
        return cha;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值