当前位置: 首页 > news >正文

2025年-G4--lc75--Best Time to Buy and Sell Stock(java版)

1.题目描述
请添加图片描述
2.思路
思路1:
请添加图片描述

在这里插入图片描述
请添加图片描述
请添加图片描述

3.java代码实现

class Solution {
    public int maxProfit(int[] prices) {
    
    // //初始化最小价格为最大值,最大利润为0

    //    int minPrice=Integer.MAX_VALUE;
    //    int maxProfit=0;

    //    //遍历价格数组
    //    for (int price : prices)
    //    {
    //     //如果当前价格更低,更新最小价格
    //     if(price<minPrice)
    //     {
    //         minPrice = price;
    //     }
    //     // 计算当前卖出时的利润
    //     else
    //     {
    //         int profit=price-minPrice;
    //         // 更新更大利润
    //         if(profit>maxProfit)
    //         {
    //             maxProfit= profit;
    //         }
    //     }
    //    }
    //    return maxProfit;
    if(prices==null ||prices.length<2)
    {
        return 0;
    }

    int minPrice=prices[0];// 初始化最小价格为第一个元素
    int maxPofit=0;

    for(int i=1;i<prices.length;i++)
    {
         // 如果当前价格比最小价格大,计算利润
         int  profit=prices[i]-minPrice;
         // 更新最小价格
        minPrice = Math.min(minPrice,prices[i]);
        
        // 更新最大利润 
        maxPofit = Math.max(maxPofit,profit);
        

    }
    return maxPofit;


    }
}

相关文章:

  • 人工智能神经网络
  • Ollama+DeepSeek+Open-WebUi
  • 在自有ARM系统上离线安装MongoDB的坎坷历程与解决方案
  • 云贝餐饮连锁V3独立版全开源+vue源码
  • Vue前端开发-Vant介绍,安装部署
  • 使用 Apache PDFBox 提取 PDF 中的文本和图像
  • deepseek_各个版本django特性
  • Python如何播放本地音乐并在web页面播放
  • C#的委托delegate与事件event
  • es6的Generator函数用法
  • 【Git】reflog实战:找回丢失的提交
  • USB2.03.0接口区分usb top工具使用
  • uniapp 打包安卓 集成高德地图
  • C#功能测试
  • Redis日志分析
  • 序列化和反序列化
  • Git从基础到进阶
  • 2025.2.17——1400
  • CHARMM-GUI EnzyDocker: 一个基于网络的用于酶中多个反应状态的蛋白质 - 配体对接的计算平台
  • 【Leetcode 热题 100】1287. 有序数组中出现次数超过25%的元素
  • 赣州蓉江新区党工委原书记王凌主动交代问题,正接受审查调查
  • 受工友诱骗为获好处费代购免税品,海口海关:两当事人被立案
  • 交通运输局男子与两名女子办婚礼?官方通报:未登记结婚,开除该男子
  • 王毅同德国外长瓦德富尔通电话
  • AI创业者聊大模型应用趋势:可用性和用户需求是关键
  • 重庆城市轨道交通拟听证调价:公布两套票价方案,正征求意见