【力扣热题100】—— Day15 买卖股票的最佳时机

LeetCode高频SQL50题解析与面试实战技巧 SQL作为数据处理的核心语言,其查询优化与高效执行是数据库领域的重点。通过窗口函数、多表关联等关键技术,可以实现复杂业务逻辑的数据分析。在技术面试中,LeetCode高频SQL50题集中考察了复杂查询构建、多表操作、窗口函数应用等核心能力,这些题目源自电商用户行为分析、社交网络关系挖掘等真实场景。掌握排名类问题的DENSE_RANK()解法、连续性问题的日期差值分组技巧,以及避免NOT IN性能陷阱等优化策略,能显著提升SQL编写效率。对于数据从业者,这些技能不仅有助于通过技术面试,更能应对实际工作中的数据 阅读详情

我只是怕搞砸了我唯一擅长的事

                                        —— 24.12.15

买卖股票的最佳时机

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。

你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。

返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。

示例 1:

输入:[7,1,5,3,6,4]
输出:5
解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。
     注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格;同时,你不能在买入前卖出股票。
示例 2:
输入:prices = [7,6,4,3,1]
输出:0
解释:在这种情况下, 没有交易完成, 所以最大利润为 0。

方法一 枚举 + 维护前缀最小值

思路与算法

        我们来假设自己来购买股票。随着时间的推移,每天我们都可以选择出售股票与否。那么,假设在第 i 天,如果我们要在今天卖股票,那么我们能赚多少钱呢?

显然,如果我们真的在买卖股票,我们肯定会想:如果我是在历史最低点买的股票就好了!太好了,在题目中,我们只要用一个变量记录一个历史最低价格 minprice,我们就可以假设自己的股票是在那天买的。那么我们在第 i 天卖出股票能得到的利润就是 prices[i] - minprice。

        因此,我们只需要遍历价格数组一遍,记录历史最低点,然后在每一天考虑这么一个问题:如果我是在历史最低点买进的,那么我今天卖出能赚多少钱?当考虑完所有天数之时,我们就得到了最好的答案。


python实现

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        temp = 10000
        minPrice = temp
        maxProfit = 0
        for price in prices:
            maxProfit = max(price - minPrice, maxProfit)
            minPrice = min(price, minPrice)
        return maxProfit

​


Java实现

class Solution {
    public int maxProfit(int[] prices) {
        int minPrice = Integer.MAX_VALUE;
        int maxProfit = 0;
        for(int i = 0; i < prices.length; i++){
            if(prices[i] < minPrice){
                // 找到最小值买入
                minPrice = prices[i];
            }else if(prices[i] - minPrice > maxProfit){
                // 更新最大值
                maxProfit = prices[i] - minPrice;
            }
        }
        return maxProfit;
    }
}

​

前端100道八股文+50道场景题 闭包是指一个函数能够访问它外部函数作用域中的变量,即使外部函数已经执行完毕。形成闭包需要三个条件:函数嵌套、内部函数引用外部变量、外部函数返回内部函数。闭包的主要作用有三个:第一,实现数据私有化。比如可以用闭包创建私有变量,外部无法直接访问,只能通过特定方法操作。第二,模块化。可以用闭包封装代码,只暴露需要的接口。第三,函数柯里化和防抖节流等高级技巧都会用到闭包。闭包的缺点是可能造成内存泄漏。因为闭包引用的外部变量不会被垃圾回收,如果大量使用闭包且不及时清理,会占用过多内存。 阅读详情

相关推荐

【gateway nc adapter虚拟网卡 win11 联想】问题的解决

由于需要登录公司内网,于是启用奇安信VPN。但启动后报出网关未连接的问题,于是我检查了我的网络适配器,并尝试解决,以下给出几种我实践过程中的行动,并附带最后成功的解决方法。

m0_73602417的博客 6582

LeetCode刷题day58

LeetCode刷题day58

LXYDSF的博客 3133

Mediapipe入门——搭建姿态检测模型并实时输出人体关节点3d坐标(2024.1.4更新)

Mediapipe入门,利用mediapipe搭建人体整体检测模型,并输出右手21个关节点的坐标;mp_holistic.Holistic函数理解,mp_holistic.Holistic.process函数理解;mp.solutions.drawing_utils.draw_landmarks函数理解;Mediapipe实时姿态估计,3d骨架铰接图,matplotlib和Mediapipe绘图

kalakalabala的博客 6万+

【LeetCode】26 买卖股票的最佳时机

码上生花,ECharts 作品展示赛正式启动!>>> ...

JaneRoad 374

Android应用隐私合规自动化检测:Frida与Camille实战指南

在移动应用安全与隐私合规领域,动态代码插桩技术已成为核心检测手段。其原理是通过运行时注入,实时监控和修改应用行为,从而绕过传统静态分析的局限。这项技术的核心价值在于能够精准捕获应用在运行时的敏感数据调用与网络传输行为,为隐私合规审计、安全测试提供直接证据。在实际应用场景中,它尤其适用于自动化检测违规收集个人信息、追踪数据流向等任务。本文聚焦于利用Frida这一动态插桩框架,结合Camille隐私合规检测工具集,构建自动化监控环境。通过注入JavaScript代码,实现对Android敏感API(如获取设备标

weixin_34254464的博客 389

使用再生龙还原镜像文件到硬盘

1. 把制作好的再生龙光盘插入需要的电脑,开机按F4使用再生龙启动2. 选择默认的:Clonezailla live(Default settings,VGA 800*600),然后等待几分钟 3. 选择语言:简体中文 4. 选择不修改键盘映射 5. 选择使用再生龙          6. 选择硬盘/分区(存到/来自)镜像文件,此选项既可以制作镜像,也可以恢复镜像。 7. 使用本机的分区     ...

weixin_42168893的博客 1万+

LeetCode 121. 买卖股票的最佳时机

给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。 你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。 返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。 示例 1: 输入:[7,1,5,3,6,4] 输出:5 解释:在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 注意利润不能是 7-1

tomjobs的博客 1765

手把手教你学PCIE(5.1)--pcie固件初始化的硬件初始化

PCIe 固件初始化的硬件初始化是一个复杂但至关重要的过程。通过正确配置 PCIe 控制器和相关硬件,可以确保系统的稳定性和性能。以上步骤和示例代码提供了一个基本的框架,实际开发中可能需要根据具体的硬件和需求进行调整和优化。

MHD0815的博客 1696

每日一题121-买卖股票的最佳时机

1.题目详情 给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。 你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。 返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。 2.解题思路 动态规划(解析来源于力扣) 动态规划一般分为一维、二维、多维(使用状态压缩),对应形式为 dp(i)dp(i)、dp(i)(j)dp(i)(j)、二进制dp(i)(j)二进制dp

weixin_46398446的博客 713

【Block总结】DiffAttention,差分注意力融入CLIP架构,抑制噪声,增强对相关特征的关注|即插即用

DiffCLIP通过微小的结构改动实现了显著的性能提升,为多模态模型的轻量化与高效化提供了新范式。

AI浩 1569

微信电脑版本不会自动下载图片吗?——没有找到解决方法。——只会默认下载doc等文件,图片不行,需要自己另存为——有什么办法解决吗?

微信电脑版本不会自动下载图片吗?——没有找到解决方法。——只会默认下载doc等文件,图片不行,需要自己另存为——有什么办法解决吗?此外,用户还可以选择将接收到的图片、视频和文件保存到指定的文件夹中。‌用户可以在微信设置中调整这一设置。

qq_15963745的博客 5131

leetcode每日一题·买卖股票问题(Python)

leetcode每日一题·买卖股票问题(Python) 买卖股票的最佳时机(股票最大利润) 题目链接 给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。 你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。 返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。 暴力法 直接遍历两次,记录最大利润 class Solution: def maxProfit(s

zjlwdqca的博客 2185

某东详情页h5st 算法分析

某东详情页h5st 算法分析

自成背后的博客 1万+

LeetCode100天Day15-买卖股票II与跳跃游戏

本文解析了LeetCode两道经典题目:买卖股票II和跳跃游戏。买卖股票问题采用贪心算法,通过收集所有正利润实现最大收益;跳跃游戏则运用逆向思维,从终点反推判断可达性。文章详细讲解了两种解题思路、代码实现及复杂度分析,并通过示例演示执行流程,帮助读者掌握贪心策略和逆向推导技巧。

2502_91523773的博客 866

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

老版QQ原生表情gif动态

这是老版的QQ表情,不过全是动态的的,Windows照片查看器是不会动的,可以右击用浏览器打开查看,再说一遍是老版的,只是分享给宁愿用老版也要动态的人。

必知的10个SAA-C03考试常见陷阱:aws-certified-solutions-architect-associate-brasil中SNS vs SQS等对照清单

如果你正在备考 AWS Certified Solutions Architect Associate(SAA-C03),最怕的就是"两个选项都看着对"。开源项目 aws-certified-solutions-architect-associate-brasil 用一套巴西葡萄牙语资料,把考试中最常踩的 10 个对比陷阱整理成了对照清单——从 SNS vs SQS 到 RDS Multi-AZ

gitblog_01164的博客 1108

全球国家地区城市数据

MySQL全球国家地区城市数据报。。。。。。。。。。。。

CodeTop100 Day5

这类题都有模板,定义回溯API,定义访问路径布尔类型数组,API里面返回条件是二维数组中的一维数组长度等于nums.length,就加入结果,每次遍历路径将该路径记录,然后遍历完该路径进行回退,remove,前一个路径结点清空,遍历完返回结果就ok了。这个转移怎么理解呢,就是当天有股票是怎么转移的,没股票是怎么转移的,然后k的理解,转移时候最大k一定是从最大为k-1转移。dp[...][0][0]=0这时候没有交易且无股票为0,dp[..][0][1]=min 这时候不可能有股票为负无穷。

Rsy0824的博客 685

算法营day15--贪心算法

选择排序 思路:选择排序也是一种贪心算法,每次选择当前未排序数组中的最小值,和未排序数组的头进行交换。 代码: void mysel_sort(vector<int> &nums){ for (int i = 0; i < nums.size()-1; ++i) { int smallest = i; for(int j = i+1;j<nums.size();++j) { if(nums[j]

王学门徒 219

wy的leetcode刷题记录_Day16

leetcode

m0_54015435的博客 233

10天高效刷完LeetCode Hot100:算法面试冲刺指南

算法面试是技术求职中的关键环节,LeetCode Hot100作为经典题库覆盖了90%以上的大厂考点。通过刻意练习建立算法模式的肌肉记忆,能显著提升解题效率。本文以动态规划和回溯算法等核心题型为例,详解如何用'三明治学习法'实现每日12题的高效训练,包括题目分类策略、五步刷题法和错题管理系统。特别针对数组操作和二叉树遍历等高频考点,提供时间规划与面试模拟的实战技巧,帮助开发者在短期内突破算法瓶颈。

weixin_32642109的博客 365

LeetCode HOT 100Ⅰ

hot100

weixin_45876739的博客 778

【自用】LeetCode Hot100 刷题总结

滑动窗口的本质,是在一个线性数据结构(如数组、字符串)上维护一个连续的区间(子数组/子串)。右指针 (right:负责扩张窗口,引入新的元素。左指针 (left:负责收缩窗口,在条件被破坏时移除旧元素。威力:它把原本需要暴力枚举 O(N2)O(N2) 的子区间问题,优化到了O(N)O(N) 的线性时间。因为每个元素最多被right访问一次,被left访问一次。定义:前缀和S[i]表示原数组nums中从第 0 个元素加到第 i-1 个元素的总和(即威力:如果不使用前缀和,求任意子数组。

wcxcoding的博客 253

代码随想录五刷day12

i <= m;i <= n;邻接表i <= n;;

ResNet156的博客 395

股票价格跨度算法:单调栈在金融分析中的应用

股票价格跨度是金融技术分析中的基础指标,用于衡量当前价格相对于历史价格的位置。其核心原理是通过维护一个单调递减栈,高效计算连续小于等于当前价格的天数。这种基于单调栈的算法优化将时间复杂度从O(n)降低到摊还O(1),特别适合处理高频交易数据。在量化金融领域,该指标广泛应用于趋势分析、支撑位识别和交易信号生成。结合LeetCode 901题的经典解法,展示了如何将数据结构优化应用于金融工程实践,其中单调栈和算法复杂度分析是解决问题的关键。

weixin_33798152的博客 454

LeetCode算法题之121. Best Time to Buy and Sell Stock(easy)【Python3动态规划题解】

题目描述: Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the st...

DaMoWangZQ的博客 445

算法设计与分析课作业【week11】leetcode--动态规划简单难度题目合集

题目1--121. Best Time to Buy and Sell Stock Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (i.e....

weixin_36332464的博客 408

个人博客目录

个人博客传送门

nanashi_F的博客 532
上一篇: 【力扣热题100】—— Day14 杨辉三角
下一篇: 【力扣热题100】—— Day16.二叉树的直径
L_cl
博客等级 码龄4年 5161粉丝 572原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值