博客
关于我
【力扣】[热题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/

    你可能感兴趣的文章
    nowcoder—Beauty of Trees
    查看>>
    np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
    查看>>
    np.power的使用
    查看>>
    NPM 2FA双重认证的设置方法
    查看>>
    npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
    查看>>
    npm build报错Cannot find module ‘webpack‘解决方法
    查看>>
    npm ERR! ERESOLVE could not resolve报错
    查看>>
    npm ERR! fatal: unable to connect to github.com:
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
    查看>>
    npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
    查看>>
    npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
    查看>>
    npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
    查看>>
    npm install CERT_HAS_EXPIRED解决方法
    查看>>
    npm install digital envelope routines::unsupported解决方法
    查看>>
    npm install 卡着不动的解决方法
    查看>>
    npm install 报错 EEXIST File exists 的解决方法
    查看>>
    npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
    查看>>
    npm install 报错 Failed to connect to github.com port 443 的解决方法
    查看>>
    npm install 报错 fatal: unable to connect to github.com 的解决方法
    查看>>
    npm install 报错 no such file or directory 的解决方法
    查看>>