当前位置: 首页 > news >正文

买卖股票的最佳时机 - 合集

*************

C++

买卖股票问题合集

*************

Since I have finished some stocks problems. I wanna make a list of the stocks to figure out the similarities.

Here is the storks topucs list, from easy to hard:

121. 买卖股票的最佳时机 - 力扣(LeetCode)

122. 买卖股票的最佳时机 II - 力扣(LeetCode)

123. 买卖股票的最佳时机 III - 力扣(LeetCode)

188. 买卖股票的最佳时机 IV - 力扣(LeetCode)

714. 买卖股票的最佳时机含手续费 - 力扣(LeetCode)

309. 买卖股票的最佳时机含冷冻期 - 力扣(LeetCode)\

here I will introduce a very professional upper about stocks - bilibili ID - 小Lin说

In my opinion, topic 309 is the most harder one and I fail to solve it.

Start from the EZ one:121. 买卖股票的最佳时机 - 力扣(LeetCode)icon-default.png?t=O83Ahttps://leetcode.cn/problems/best-time-to-buy-and-sell-stock/description/

With no hesitation, only two states in a day, to be or not to be, in other word, Buy or sale.

Make int Buy is the profit in the day i while buy one;

Make int Sale is the profit in the day i while sale one;

If I have stocks today, two situations,  1 is that you bought it days before today; 2 is that you buy it today. So today's max profit is max(Buy, - prices[i]);

If I donnot have stocks today, two situations, 1 is that you sale it the day before today and today you donnot plan to buy too, so today's profit is int Sale; 2 is you sale iyt today, and today's profit is int Buy + prices[i];

the most important concept is here:

Buy = max(Buy, - prices[i]); // 如果今天买入股票,利润是之前不持有股票的最大利润减去今天的价格
Sale = max(Sale, Buy + prices[i]); // 如果今天卖出股票,利润是之前持有股票的最大利润加上今天的价格

 The whole code is as follow.

class Solution {
public:int maxProfit(vector<int>& prices) {if (prices.empty()) return 0; // 如果价格数组为空,返回0int Buy = -prices[0]; // 最初买入股票,利润为负数,因为还没有卖出int Sale = 0; // 最初不卖出股票,利润为0for (int i = 1; i < prices.size(); i++) {Buy = max(Buy, - prices[i]); // 如果今天买入股票,利润是之前不持有股票的最大利润减去今天的价格Sale = max(Sale, Buy + prices[i]); // 如果今天卖出股票,利润是之前持有股票的最大利润加上今天的价格}return Sale; // 返回不持有股票的最大利润}
};

Go on. If you can trade twice during the whole period.

123. 买卖股票的最佳时机 III - 力扣(LeetCode)icon-default.png?t=O83Ahttps://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iii/description/

 That is easy to write, just add another group of trading:

 If trading once during the whole period, the equation is as follow.

firstBuy = max(firstBuy, - prices[i]); // 如果今天买入股票,利润是之前不持有股票的最大利润减去今天的价格
firstSale = max(firstSale, firstBuy + prices[i]); // 如果今天卖出股票,利润是之前持有股票的最大利润加上今天的价格

now we have the second trading. As is known, second always comes after first:

firstBuy = max(firstBuy, - prices[i]); // 如果今天买入股票,利润是之前不持有股票的最大利润减去今天的价格
firstSale = max(firstSale, firstBuy + prices[i]); // 如果今天卖出股票,利润是之前持有股票的最大利润加上今天的价格// 加上第二次交易
secondBuy = max(secondBuy, firstSale - prices[i]);
secondSale = max(secondSale, prices[i] + secondBuy);

And the other code remains:

class Solution {
public:int maxProfit(vector<int>& prices) {int n = prices.size(); // get the lengthint firstBuy = - prices[0];int firstSale = 0;int secondBuy = - prices[0];int secondSale = 0;// do sth. herefor (int i = 1; i < n; i++){firstBuy = max(firstBuy, - prices[i]); // 如果今天买入股票,利润是之前不持有股票的最大利润减去今天的价格firstSale = max(firstSale, firstBuy + prices[i]); // 如果今天卖出股票,利润是之前持有股票的最大利润加上今天的价格// 加上第二次交易secondBuy = max(secondBuy, firstSale - prices[i]);secondSale = max(secondSale, prices[i] + secondBuy);}return secondSale;}
};

What if trading times is k?

188. 买卖股票的最佳时机 IV - 力扣(LeetCode)icon-default.png?t=O83Ahttps://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iv/description/

the most important algorithm remains same:

Buy = max(Buy, - prices[i]); // 如果今天买入股票,利润是之前不持有股票的最大利润减去今天的价格
Sale = max(Sale, Buy + prices[i]); // 如果今天卖出股票,利润是之前持有股票的最大利润加上今天的价格

loops buy-sale group:

for (int i = 0; i < n; i++) {for (int j = 1; j <= k; j++) {// 更新买入状态,即在第i天买入第j次的最大利润buy[j] = max(buy[j], sell[j - 1] - prices[i]);// 更新卖出状态,即在第i天卖出第j次的最大利润sell[j] = max(sell[j], buy[j] + prices[i]);}}

the rest of the code remains.

class Solution {
public:int maxProfit(int k, vector<int>& prices) {int n = prices.size();vector<int> buy(k + 1, INT_MIN), sell(k + 1, 0);for (int i = 0; i < n; i++) {for (int j = 1; j <= k; j++) {// 更新买入状态,即在第i天买入第j次的最大利润buy[j] = max(buy[j], sell[j - 1] - prices[i]);// 更新卖出状态,即在第i天卖出第j次的最大利润sell[j] = max(sell[j], buy[j] + prices[i]);}}// 最后返回卖出状态的最大值,即进行k次交易的最大利润return sell[k];}};

What if the trading times are free?

122. 买卖股票的最佳时机 II - 力扣(LeetCode)icon-default.png?t=O83Ahttps://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/description/

That comes easy. Buy in every low price and salt out when price is highher:

class Solution {
public:int maxProfit(vector<int>& prices) {int n = prices.size();if (n <= 1) return 0;  // 如果数组为空或只有一个元素,直接返回0int profit = 0;for (int i = 0; i < n - 1; i++) {if (prices[i + 1] > prices[i]) {profit += prices[i + 1] - prices[i];}}return profit;}
};

What if you have to pay trading fee every time?

714. 买卖股票的最佳时机含手续费 - 力扣(LeetCode)icon-default.png?t=O83Ahttps://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/

It looks like  122. 买卖股票的最佳时机 II - 力扣(LeetCode), however make   profit += prices[i + 1] - prices[i] - fee; doesnot work.

 Think different, there is a treading time k, makes the max profit. So it is more like 188. 买卖股票的最佳时机 IV - 力扣(LeetCode)

I do remember the mostimportant algorithm

Buy = max(Buy, - prices[i]); // 如果今天买入股票,利润是之前不持有股票的最大利润减去今天的价格
Sale = max(Sale, Buy + prices[i]); // 如果今天卖出股票,利润是之前持有股票的最大利润加上今天的价格
class Solution {
public:int maxProfit(vector<int>& prices, int fee) {int n = prices.size();if (n <= 1) return 0;int Sale = 0; // 不持有股票的最大利润int Buy = -prices[0]; // 持有股票的最大利润for (int i = 1; i < n; i++) {int current_Sale = max(Sale, Buy + prices[i] - fee);int current_Buy = max(Buy, Sale - prices[i]);Sale = current_Sale;Buy = current_Buy;}return Sale;}
};

And the one I hate comes:309. 买卖股票的最佳时机含冷冻期 - 力扣(LeetCode)icon-default.png?t=O83Ahttps://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/

 Of course, like the last one, the most important algorithm is as follow.

Buy = max(Buy, - prices[i]); // 如果今天买入股票,利润是之前不持有股票的最大利润减去今天的价格
Sale = max(Sale, Buy + prices[i]); // 如果今天卖出股票,利润是之前持有股票的最大利润加上今天的价格

For every special day , there is 2 states

  1. have stocks
  2. have not stocks

for having a stock

  1. have stocks 
  •  buy today
  • freeze day before today

for not having a stock

  • sale today
  • sale day before today and buy  no stocks today

But if I sale the stocks today, I cannot buy one tomorrow. So for not having stocks have two situations:

  • sold: the profit of you donnot have a stock but in a freeze period which you cannot buy one
  • rest: the profit of you donnot have a stock and not in a freeze period which you can buy one

so the code is easy

buy = max(buy, rest - prices[i]), the profit of you bought before or you buy todaysold = buy + price[i]rest = max(rest, sold)

and loop i

class Solution {
public:int maxProfit(vector<int>& prices) {if (prices.empty()) return 0;int n = prices.size();// 初始状态int buy = -prices[0];int sold = 0;int rest = 0;for (int i = 1; i < n; ++i) {int new_buy = max(buy, rest - prices[i]);int new_sold = buy + prices[i];int new_rest = max(rest, sold);buy = new_buy;sold = new_sold;rest = new_rest;}return max(sold, rest);}
};

the most important is as follow:
 

Buy = max(Buy, - prices[i]); // 如果今天买入股票,利润是之前不持有股票的最大利润减去今天的价格
Sale = max(Sale, Buy + prices[i]); // 如果今天卖出股票,利润是之前持有股票的最大利润加上今天的价格

相关文章:

买卖股票的最佳时机 - 合集

************* C 买卖股票问题合集 ************* Since I have finished some stocks problems. I wanna make a list of the stocks to figure out the similarities. Here is the storks topucs list, from easy to hard: 121. 买卖股票的最佳时机 - 力扣&#xff08;L…...

lshw学习——简单介绍

文章目录 简介核心结构扫描设备原理scan_abiscan_burnerscan_cdromscan_cpufreqscan_cpuidscan_cpuinfoscan_device_treescan_diskscan_displayscan_dmiscan_fatscan_fbscan_graphicsscan_idescan_ideraidscan_inputscan_isapnpscan_lvmscan_memoryscan_mmcscan_mountsscan_net…...

深入理解Kafka:核心设计与实践原理读书笔记

目录 初识Kafka基本概念安装与配置ZooKeeper安装与配置Kafka的安装与配置 生产与消费服务端参数配置 生产者客户端开发消息对象 ProducerRecord必要的参数配置发送消息序列化分区器生产者拦截器 原理分析整体架构元数据的更新 重要的生产者参数acksmax.request.sizeretries和re…...

OnOn-WebSsh (昂~昂~轻量级WebSSH) 可实现 网页 中的 ssh 客户端操作,支持多用户多线程操作 ssh 持久化

OnOn-WebSsh springBoot 服务器 开源技术栏 OnOn-WebSsh (昂昂轻量级WebSSH) 可实现 网页 中的 ssh 客户端操作&#xff0c;支持多用户多线程操作 支持指定ssh 连接, 支持sftp 以及 ssh 持久化. OnOn-WebSSH (OnOn Lightweight WebSSH) enables SSH client operations withi…...

LDP+LBP代码解析及应用场景分析

代码整体结构与功能概述 这段 C 代码主要实现了两个图像特征提取算法&#xff0c;分别是局部方向模式&#xff08;Local Directional Pattern&#xff0c;LDP&#xff09;和多分块局部二值模式&#xff08;Multi-Block Local Binary Pattern&#xff0c;Multi-Block LBP&#…...

51c视觉~合集33

我自己的原文哦~ https://blog.51cto.com/whaosoft/12163849 #Robin3D 3D场景的大语言模型&#xff1a;在鲁棒数据训练下的3DLLM新SOTA! 论文地址&#xff1a;https://arxiv.org/abs/2410.00255代码将开源&#xff1a;https://github.com/WeitaiKang/Robin3D 介绍 多模态…...

element plus的table组件,点击table的数据是,会出现一个黑色边框

在使用 Element Plus 的 Table 组件时&#xff0c;如果你点击表格数据后出现了一个黑色边框&#xff0c;这通常是因为浏览器默认的焦点样式&#xff08;outline&#xff09;被触发了。如图&#xff1a; 你可以通过自定义 CSS 来隐藏这个黑色边框&#xff0c;代码如下&#xff1…...

springmvc的拦截器,全局异常处理和文件上传

拦截器: 拦截不符合规则的&#xff0c;放行符合规则的。 等价于过滤器。 拦截器只拦截controller层API接口。 如何定义拦截器。 定义一个类并实现拦截器接口 public class MyInterceptor implements HandlerInterceptor {public boolean preHandle(HttpServletRequest reque…...

【coredump】笔记

coredump 是什么&#xff1f;最标准的解释是什么&#xff1f; Core dump&#xff08;也称为 core 文件或 core dump 文件&#xff09;是计算机程序在运行时崩溃时生成的文件&#xff0c;它捕获了程序在崩溃时的内存状态。这些文件通常用于调试目的&#xff0c;以帮助开发人员分…...

【Linux】磁盘空间莫名消失,找不到具体原因的思路

磁盘空间莫名消失&#xff0c;找不到具体原因的思路 先说下常见的几种原因&#xff1a; 1、删除的文件未释放空间 2、日志或过期文件未及时清理 3、inode导致 4、隐藏文件夹或者目录 6、磁盘碎片 最后一种单独介绍。 环境&#xff1a;情况是根分区&#xff08;/&#xf…...

智能体实战(需求分析助手)一、需求概述及迭代规划

需求分析助手开发迭代规划 功能概述 需求分析助手是一款基于大模型的智能系统,旨在帮助用户高效完成需求获取、需求分析、需求文档编写及需求验证的全流程工作。通过对用户输入的智能处理和分析,需求分析助手能够简化需求管理流程,并根据不同业务场景提供定制化支持。 核心…...

idea | maven项目标红解决方案 | 强制刷新所有依赖

场景&#xff1a;父pom多模块&#xff0c;新增时&#xff0c;依赖正常&#xff0c;但是application.yml看起来没被springboot识别&#xff0c;试过rebuild、重开idea清除缓存&#xff0c;重新maven面板reload all maven projects, 试过pom文件的依赖先移除再重新粘贴导入进来&a…...

*【每日一题 基础题】 [蓝桥杯 2023 省 B] 飞机降落

题目描述 N 架飞机准备降落到某个只有一条跑道的机场。其中第 i 架飞机在 Ti 时刻到达机场上空&#xff0c;到达时它的剩余油料还可以继续盘旋 Di 个单位时间&#xff0c;即它最早可以于 Ti 时刻开始降落&#xff0c;最晚可以于 Ti Di 时刻开始降落。降落过程需要 Li个单位时间…...

在Windows本地用网页查看编辑服务器上的 jupyter notebook

​ Motivation: jupyter notebook 可以存中间变量&#xff0c;方便我调整代码&#xff0c;但是怎么用服务器的GPU并在网页上查看编辑呢&#xff1f; 参考 https://zhuanlan.zhihu.com/p/440080687 服务端(Ubuntu)&#xff1a; 激活环境 source activate my_env安装notebook …...

OpenCV圆形标定板检测算法findGrid原理详解

OpenCV的findGrid函数检测圆形标定板的流程如下: class CirclesGridClusterFinder {CirclesGridClusterFinder(const CirclesGridClusterFinder&); public:CirclesGridClusterFinder...

自动图像标注可体验

✨✨ 欢迎大家来访Srlua的博文&#xff08;づ&#xffe3;3&#xffe3;&#xff09;づ╭❤&#xff5e;✨✨ &#x1f31f;&#x1f31f; 欢迎各位亲爱的读者&#xff0c;感谢你们抽出宝贵的时间来阅读我的文章。 我是Srlua小谢&#xff0c;在这里我会分享我的知识和经验。&am…...

武汉市电子信息与通信工程职称公示了

2024年武汉市电子信息与通信工程专业职称公示了&#xff0c;本次公示通过人员有109人。 基本这已经是今年武汉市工程相关职称最后公示了&#xff0c;等待出证即可。 为什么有人好奇&#xff0c;一样的资料&#xff0c;都是业绩、论文等&#xff0c;有的人可以过&#xff0c;有的…...

Ansible基本用法

Ansible 1 Ansible概念 Ansible是一个基于Python开发的配置管理和应用部署工具&#xff0c;现在也在自动化管理领域大放异彩。它融合了众多老牌运维工具的优点&#xff0c;Pubbet和Saltstack能实现的功能&#xff0c;Ansible基本上都可以实现。 Ansible能批量配置、部署、管理…...

MFC 应用程序语言切换

在开发多语言支持的 MFC 应用程序时&#xff0c;如何实现动态语言切换是一个常见的问题。在本文中&#xff0c;我们将介绍两种实现语言切换的方式&#xff0c;并讨论其优缺点。同时&#xff0c;我们还会介绍如何通过保存配置文件来记住用户的语言选择&#xff0c;以及如何在程序…...

Swift 的动态性

Swift 的动态性指的是 Swift 编程语言支持运行时操作的一些特性&#xff0c;使得代码的行为能够在运行时作出一定的调整或决策。这些特性通常可以让程序在运行时动态地添加、删除或修改对象的属性、方法等&#xff0c;而不是在编译时完全确定。 Swift 的动态性主要体现在以下几…...

MPNet:旋转机械轻量化故障诊断模型详解python代码复现

目录 一、问题背景与挑战 二、MPNet核心架构 2.1 多分支特征融合模块(MBFM) 2.2 残差注意力金字塔模块(RAPM) 2.2.1 空间金字塔注意力(SPA) 2.2.2 金字塔残差块(PRBlock) 2.3 分类器设计 三、关键技术突破 3.1 多尺度特征融合 3.2 轻量化设计策略 3.3 抗噪声…...

多模态2025:技术路线“神仙打架”,视频生成冲上云霄

文&#xff5c;魏琳华 编&#xff5c;王一粟 一场大会&#xff0c;聚集了中国多模态大模型的“半壁江山”。 智源大会2025为期两天的论坛中&#xff0c;汇集了学界、创业公司和大厂等三方的热门选手&#xff0c;关于多模态的集中讨论达到了前所未有的热度。其中&#xff0c;…...

边缘计算医疗风险自查APP开发方案

核心目标:在便携设备(智能手表/家用检测仪)部署轻量化疾病预测模型,实现低延迟、隐私安全的实时健康风险评估。 一、技术架构设计 #mermaid-svg-iuNaeeLK2YoFKfao {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}#mermaid-svg…...

2024年赣州旅游投资集团社会招聘笔试真

2024年赣州旅游投资集团社会招聘笔试真 题 ( 满 分 1 0 0 分 时 间 1 2 0 分 钟 ) 一、单选题(每题只有一个正确答案,答错、不答或多答均不得分) 1.纪要的特点不包括()。 A.概括重点 B.指导传达 C. 客观纪实 D.有言必录 【答案】: D 2.1864年,()预言了电磁波的存在,并指出…...

JVM垃圾回收机制全解析

Java虚拟机&#xff08;JVM&#xff09;中的垃圾收集器&#xff08;Garbage Collector&#xff0c;简称GC&#xff09;是用于自动管理内存的机制。它负责识别和清除不再被程序使用的对象&#xff0c;从而释放内存空间&#xff0c;避免内存泄漏和内存溢出等问题。垃圾收集器在Ja…...

令牌桶 滑动窗口->限流 分布式信号量->限并发的原理 lua脚本分析介绍

文章目录 前言限流限制并发的实际理解限流令牌桶代码实现结果分析令牌桶lua的模拟实现原理总结&#xff1a; 滑动窗口代码实现结果分析lua脚本原理解析 限并发分布式信号量代码实现结果分析lua脚本实现原理 双注解去实现限流 并发结果分析&#xff1a; 实际业务去理解体会统一注…...

OPenCV CUDA模块图像处理-----对图像执行 均值漂移滤波(Mean Shift Filtering)函数meanShiftFiltering()

操作系统&#xff1a;ubuntu22.04 OpenCV版本&#xff1a;OpenCV4.9 IDE:Visual Studio Code 编程语言&#xff1a;C11 算法描述 在 GPU 上对图像执行 均值漂移滤波&#xff08;Mean Shift Filtering&#xff09;&#xff0c;用于图像分割或平滑处理。 该函数将输入图像中的…...

处理vxe-table 表尾数据是单独一个接口,表格tableData数据更新后,需要点击两下,表尾才是正确的

修改bug思路&#xff1a; 分别把 tabledata 和 表尾相关数据 console.log() 发现 更新数据先后顺序不对 settimeout延迟查询表格接口 ——测试可行 升级↑&#xff1a;async await 等接口返回后再开始下一个接口查询 ________________________________________________________…...

【笔记】WSL 中 Rust 安装与测试完整记录

#工作记录 WSL 中 Rust 安装与测试完整记录 1. 运行环境 系统&#xff1a;Ubuntu 24.04 LTS (WSL2)架构&#xff1a;x86_64 (GNU/Linux)Rust 版本&#xff1a;rustc 1.87.0 (2025-05-09)Cargo 版本&#xff1a;cargo 1.87.0 (2025-05-06) 2. 安装 Rust 2.1 使用 Rust 官方安…...

MacOS下Homebrew国内镜像加速指南(2025最新国内镜像加速)

macos brew国内镜像加速方法 brew install 加速formula.jws.json下载慢加速 &#x1f37a; 最新版brew安装慢到怀疑人生&#xff1f;别怕&#xff0c;教你轻松起飞&#xff01; 最近Homebrew更新至最新版&#xff0c;每次执行 brew 命令时都会自动从官方地址 https://formulae.…...