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

    你可能感兴趣的文章
    nmap指纹识别要点以及又快又准之方法
    查看>>
    Nmap渗透测试指南之指纹识别与探测、伺机而动
    查看>>
    Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
    查看>>
    NMAP网络扫描工具的安装与使用
    查看>>
    NMF(非负矩阵分解)
    查看>>
    nmon_x86_64_centos7工具如何使用
    查看>>
    NN&DL4.1 Deep L-layer neural network简介
    查看>>
    NN&DL4.3 Getting your matrix dimensions right
    查看>>
    NN&DL4.7 Parameters vs Hyperparameters
    查看>>
    NN&DL4.8 What does this have to do with the brain?
    查看>>
    nnU-Net 终极指南
    查看>>
    No 'Access-Control-Allow-Origin' header is present on the requested resource.
    查看>>
    NO 157 去掉禅道访问地址中的zentao
    查看>>
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>