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

    你可能感兴趣的文章
    npm安装crypto-js 如何安装crypto-js, python爬虫安装加解密插件 找不到模块crypto-js python报错解决丢失crypto-js模块
    查看>>
    npm安装教程
    查看>>
    npm报错Cannot find module ‘webpack‘ Require stack
    查看>>
    npm报错Failed at the node-sass@4.14.1 postinstall script
    查看>>
    npm报错fatal: Could not read from remote repository
    查看>>
    npm报错File to import not found or unreadable: @/assets/styles/global.scss.
    查看>>
    npm报错TypeError: this.getOptions is not a function
    查看>>
    npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
    查看>>
    npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
    查看>>
    npm版本过高问题
    查看>>
    npm的“--force“和“--legacy-peer-deps“参数
    查看>>
    npm的安装和更新---npm工作笔记002
    查看>>
    npm的常用操作---npm工作笔记003
    查看>>
    npm的常用配置项---npm工作笔记004
    查看>>
    npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
    查看>>
    npm编译报错You may need an additional loader to handle the result of these loaders
    查看>>
    npm设置淘宝镜像、升级等
    查看>>
    npm设置源地址,npm官方地址
    查看>>
    npm设置镜像如淘宝:http://npm.taobao.org/
    查看>>
    npm配置安装最新淘宝镜像,旧镜像会errror
    查看>>