算法训练 第三周

一、买卖股票的最佳时机

本题给了我们一个数组,这个数组的第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)。
相关推荐
tryxr1 小时前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_32 小时前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
Selvaggia2 小时前
DMD(Distribution Matching Distillation,分布匹配蒸馏)
算法
Navigator_Z2 小时前
LeetCode //C - 1255. Maximum Score Words Formed by Letters
c语言·算法·leetcode
All for pursuit.2 小时前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.2 小时前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
wzdark3 小时前
数据压缩算法的时间复杂度与压缩率权衡4
算法
小陈phd3 小时前
深入理解agent学习笔记(一)——现代agent介绍
人工智能·算法
晴天的雨.9926 小时前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
aramae13 小时前
MySQL复合查询(8)
java·c语言·开发语言·后端·算法