算法训练 第三周

一、买卖股票的最佳时机

本题给了我们一个数组,这个数组的第i个元素表示股票第i天的价格,要求我们选择一天买入股票,并在这天之后的某一天卖出,问我们何时能获得最大利润。

1.循环嵌套

我们可以循环遍历所有买入的价格,再遍历买入天之后的价格,记录所有能获得利润的大小,最后比较产生最大值,但是这种方法在leetcode上会超时,代码如下:

java 复制代码
class Solution {
    public int maxProfit(int[] prices) {
        int max = 0;
        for(int i = 0; i < prices.length; i++) {
            for(int j = i + 1; j < prices.length; j++) {
                if(prices[j] > prices[i] && prices[j] - prices[i] > max) {
                    max = prices[j] - prices[i];
                }
            }
        }
        return max;
    }
}

复杂度分析

  • 时间复杂度:O(n^2)。
  • 空间复杂度:O(1)。

2.一次循环

我们只需要在一次循环中动态记录价格最小的一天并不断更新,之后在遍历到它之后的比它高的价格时进行记录,最后找出最大利润即可,代码如下:

java 复制代码
class Solution {
    public int maxProfit(int[] prices) {
        int max = 0;
        int min = prices[0];
        for(int i = 0; i < prices.length; i++) {
            if(prices[i] < min) {
                min = prices[i];
            }
            if(prices[i] > min && prices[i] - min > max) {
                max = prices[i] - min;
            }
        }
        return max;
    }
}

复杂度分析

  • 时间复杂度:O(n)。
  • 空间复杂度:O(1)。
相关推荐
wenyq74 分钟前
LeetCode 2460. Apply Operations to an Array
算法·leetcode
.格子衫.1 小时前
032动态规划之区间DP——算法备赛
算法·动态规划
不会代码的小猴2 小时前
7. JSON
开发语言·c++·笔记·qt·算法·json
怪奇云呼军2 小时前
知识库也会注入指令?闪电智能VoiceAgent 如何防住 Prompt Injection
人工智能·python·算法·云计算·音视频
阿里云大数据AI技术3 小时前
基于 EMR Serverless Ray 实现 Qwen 模型批量推理实践
人工智能·算法·agent
Rambo.xia4 小时前
为什么去马赛克算法,决定了ISP的画质上限
算法·接口隔离原则
Benny_Tang4 小时前
题解:P10230 [COCI 2023/2024 #4] Lepeze
c++·算法
Geek-Chow4 小时前
06 训练管线:数据如何变成权重
人工智能·算法
我变成萤火虫4 小时前
反悔贪心(经典题目讲解)
c++·算法·贪心算法·stl·排序算法·反悔贪心