博客
关于我
【力扣】[热题HOT100] 121.买卖股票的最佳时机
阅读量:495 次
发布时间:2019-03-07

本文共 983 字,大约阅读时间需要 3 分钟。

为了解决这个问题,我们需要找到一个算法来计算从一只股票的买卖交易中获得的最大利润。我们可以通过一次遍历数组来记录最小的价格,并在之后寻找最大的价格来实现这一点。

思路分析

  • 问题分析

    • 我们需要选择一天买入股票,并在之后的某一天卖出,记录最大利润。
    • 需要确保买入和卖出发生在不同的日子。
  • 解决思路

    • Traverse数组一次。-记录遇到的最小价格。-对于每个后续的元素,计算当前价格与最小价格的利润,更新最大利润。-同时,更新最小价格,如果遇到更小的价格。
  • 优化思路

    • 通过一次遍历避免使用额外的空间。
    • 确保在每次可能的利润计算时,都跟踪最小的买入价格。
  • 代码分析

    class Solution {    public int maxProfit(vector
    &prices) { int minPrice = Integer.MAX_VALUE; int maxProfit = 0; for (int price : prices) { if (price < minPrice) { minPrice = price; } int currentProfit = price - minPrice; if (currentProfit > maxProfit) { maxProfit = currentProfit; } } return maxProfit; }}

    优化解释

    • 初始化:将minPrice初始化为Integer.MAX_VALUE,即一个非常大的数,这样第一次遇到任何价格都会被记录下来。
    • 遍历数组:对于每一个价格,首先检查是否比当前记录的minPrice小。如果是,就更新minPrice。然后计算当前价格与minPrice之间的利润,比较是否大于之前的最大利润,如果大于则更新maxProfit
    • 返回结果:经过遍历后,maxProfit会包含所有可能的最大利润值,返回它即可。

    这种方法确保了我们只需一次遍历数组,时间复杂度为O(n),空间复杂度为O(1),非常高效。

    转载地址:http://msacz.baihongyu.com/

    你可能感兴趣的文章
    NoSQL介绍
    查看>>
    NoSQL数据库概述
    查看>>
    Notadd —— 基于 nest.js 的微服务开发框架
    查看>>
    NOTE:rfc5766-turn-server
    查看>>
    Notepad ++ 安装与配置教程(非常详细)从零基础入门到精通,看完这一篇就够了
    查看>>
    Notepad++在线和离线安装JSON格式化插件
    查看>>
    notepad++最详情汇总
    查看>>
    notepad++正则表达式替换字符串详解
    查看>>
    notepad如何自动对齐_notepad++怎么自动排版
    查看>>
    Notes on Paul Irish's "Things I learned from the jQuery source" casts
    查看>>
    Notification 使用详解(很全
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>
    NotImplementedError: Could not run torchvision::nms
    查看>>
    nova基于ubs机制扩展scheduler-filter
    查看>>
    Now trying to drop the old temporary tablespace, the session hangs.
    查看>>
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    np.power的使用
    查看>>
    NPM 2FA双重认证的设置方法
    查看>>
    npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
    查看>>