买卖股票的最佳时机 IV - 困难
*************
C++
topic:188. 买卖股票的最佳时机 IV - 力扣(LeetCode)
*************
Stock angin:
![]() |
Still stocks. Intuitively, it feels hard.
For once:
class Solution {
public:int maxProfit(vector<int>& prices) {int minPrice = prices[0]; // 迄今为止遇到的最低价格int maxPro = 0; // 最大利润for (int i = 1; i < prices.size(); ++i) {// 如果当前价格比迄今为止的最低价格还低,更新最低价格if (prices[i] < minPrice) {minPrice = prices[i];} else {// 如果当前价格比最低价格高,计算利润,并更新最大利润maxPro = max(maxPro, prices[i] - minPrice);}}return maxPro;}
};
For twice.
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, prices[i] + firstBuy);// the second salesecondBuy = max(secondBuy, firstSale - prices[i]);secondSale = max(secondSale, prices[i] + secondBuy);}return secondSale;}
};
For three times:
class Solution {
public:int maxProfit(vector<int>& prices) {if (prices.empty()) return 0;int n = prices.size();// 初始化状态变量int firstBuy = -prices[0]; // 第一次买入的最大利润int firstSell = 0; // 第一次卖出的最大利润int secondBuy = -prices[0]; // 第二次买入的最大利润int secondSell = 0; // 第二次卖出的最大利润int thirdBuy = -prices[0]; // 第三次买入的最大利润int thirdSell = 0; // 第三次卖出的最大利润for (int i = 1; i < n; ++i) {// 更新第一次买入的最大利润firstBuy = max(firstBuy, -prices[i]);// 更新第一次卖出的最大利润firstSell = max(firstSell, firstBuy + prices[i]);// 更新第二次买入的最大利润secondBuy = max(secondBuy, firstSell - prices[i]);// 更新第二次卖出的最大利润secondSell = max(secondSell, secondBuy + prices[i]);// 更新第三次买入的最大利润thirdBuy = max(thirdBuy, secondSell - prices[i]);// 更新第三次卖出的最大利润thirdSell = max(thirdSell, thirdBuy + prices[i]);}return thirdSell;}
};
seems to have some idea.
I always think about one thing, if I had a mirror space, I could spare a whole life to learn how to code. After that, I enter another space to learn how to design. And go on studying playing balls and so on. However, I have only one time in this world and what I want to learn is too much with lazy mind. Rue always happen. I do some videos to record my travel and rember peoples whit me. Attracting fans sounds good but self happy means everythin. And guess what, I'll go on. Spare time from tiktok to code or work need some courage, and now I have some. All day's work just prove the plan not work, that's works do.
Chris Gardner, a stock trader, played in stocks. In the persuit of happyness, to be honest, I like this moment. Say yes to himself, in variable lives.
back to the topic, idea is find the fimilar things.
class Solution {
public:int maxProfit(vector<int>& prices) {if (prices.empty()) return 0;int n = prices.size();// 初始化状态变量int firstBuy = -prices[0]; // 第一次买入的最大利润int firstSell = 0; // 第一次卖出的最大利润int secondBuy = -prices[0]; // 第二次买入的最大利润int secondSell = 0; // 第二次卖出的最大利润int thirdBuy = -prices[0]; // 第三次买入的最大利润int thirdSell = 0; // 第三次卖出的最大利润int No.Buy = - prices[0];int No.Sale = 0;return thirdSell;}
};
the loop could do the same:
class Solution {
public:int maxProfit(vector<int>& prices) {if (prices.empty()) return 0;int n = prices.size();// 初始化状态变量int firstBuy = -prices[0]; // 第一次买入的最大利润int firstSell = 0; // 第一次卖出的最大利润int secondBuy = -prices[0]; // 第二次买入的最大利润int secondSell = 0; // 第二次卖出的最大利润int thirdBuy = -prices[0]; // 第三次买入的最大利润int thirdSell = 0; // 第三次卖出的最大利润int No.Buy = - prices[0];int No.Sale = 0;for (int i = 1; i < n; ++i) {// 更新第一次买入的最大利润firstBuy = max(firstBuy, -prices[i]);// 更新第一次卖出的最大利润firstSell = max(firstSell, firstBuy + prices[i]);// 更新第二次买入的最大利润secondBuy = max(secondBuy, firstSell - prices[i]);// 更新第二次卖出的最大利润secondSell = max(secondSell, secondBuy + prices[i]);// 更新第三次买入的最大利润thirdBuy = max(thirdBuy, secondSell - prices[i]);// 更新第三次卖出的最大利润thirdSell = max(thirdSell, thirdBuy + prices[i]);No.Buy = max(No.Buy, No.-1Buy - prices[I]);
No.Sale = max(No.Sale, No.Sale + prices[I]);}return No.Sell;}
};
Even people who doesnot know the code knows that the code doesnot runs, need some magic.
Now have two variables, i day and k times.
Define dp[i][j], the maximum profit in i days and trade j times. Then the most signifiicant eauation can be writed as
dp[i][j][sale] = max(dp[i-1][j][0], dp[i-1][j][1] + prices[i])dp[i][j][buy] = max(dp[i-1][j][1], dp[i-1][j-1][0] - prices[i])
This method can easilly understood while the array comes to three-dimentional which is really hard to caculated. I can solve two-dimentional array problems. However, the three is a little bit hard.
For each day, you have two options, have the stock or donot have the stock.
For have the stock, you may have it yesterday or buy it today. So the maximum profit is
buy[j] = max(buy[j], sell[j - 1] - prices[i]);
For donot have the stock, you may sold it yesterday or sold it today, so the maximum profit is
sell[j] = max(sell[j], buy[j] + prices[i]);
Maybe it works but I am not sure, take a example:
prices = {3, 2, 6, 5, 0, 3};
k = 2
day 0, price is 3
- j=1:
- buy[1] = max(buy[1], sell[0]-3) = max(INT_MIN, 0-3) = -3
- sell[1] = max(sell[1], buy[1]+3) = max(0, -3+3) = 0
- j=2:
- buy[2] = max(buy[2], sell[1]-3) = max(INT_MIN, 0-3) = -3
- sell[2] = max(sell[2], buy[2]+3) = max(0, -3+3) = 0
day 1,price = 2
- j=1:
- buy[1] = max(-3, sell[0]-2) = max(-3, 0-2) = -2
- sell[1] = max(0, -2+2) = 0
- j=2:
- buy[2] = max(-3, sell[1]-2) = max(-3, 0-2) = -2
- sell[2] = max(0, -2+2) = 0
day 2,price = 6:
- j=1:
- buy[1] = max(-2, 0-6) = -2
- sell[1] = max(0, -2+6) = 4
- j=2:
- buy[2] = max(-2, 4-6) = -2
- sell[2] = max(0, -2+6) = 4
day 3,price = 5:
- j=1:
- buy[1] = max(-2, 0-5) = -2
- sell[1] = max(4, -2+5) = 4
- j=2:
- buy[2] = max(-2, 4-5) = -2
- sell[2] = max(4, -2+5) = 4
day 4,price = 0:
- j=1:
- buy[1] = max(-2, 0-0) = 0
- sell[1] = max(4, 0+0) = 4
- j=2:
- buy[2] = max(-2, 4-0) = 4
- sell[2] = max(4, 4+0) = 4
day 5,price = 3:
- j=1:
- buy[1] = max(0, 0-3) = 0
- sell[1] = max(4, 0+3) = 4
- j=2:
- buy[2] = max(4, 4-3) = 4
- sell[2] = max(4, 4+3) = 7
OK, it works.
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];}
};
This week having some works to do. To be honest, this tipic is a little bit hard which takes me few days to work it.
Anyway, happy weekend.
相关文章:

买卖股票的最佳时机 IV - 困难
************* C topic:188. 买卖股票的最佳时机 IV - 力扣(LeetCode) ************* Stock angin: Still stocks. Intuitively, it feels hard. For once: class Solution { public:int maxProfit(vector<int>& prices) {in…...
linux源码编译php提示:No package ‘oniguruma‘ found
编译遇到缺少Oniguruma开发包,处理办法1 安装epel仓库、安装 Oniguruma 开发包 [rootiZwz98gb9fzslgpnomg3ceZ php-8.1.29]# yum install epel-release [rootiZwz98gb9fzslgpnomg3ceZ php-8.1.29]# yum install oniguruma oniguruma-devel 方法2:去On…...

2024技能大赛Vue流程复现
1. 关于版本的控制 vue/cli 5.0.8vscode 最新下载版本 2. 创建vuecli项目 若没有安装vuecli则可以先安装 npm install -g vue/cli # 默认下载最新版本。vue --version vue -V # 查看版本,两个选一 使用vuecli来创建一个新的vue项目,vs code打开…...

MATLAB截取图像的一部分并保存导出,在itksnap中3D展示
**问题描述:**输入nifti图像,截取图像的一部分并输出,比如截取图像的101010这一块,并导出为nii文件 inputFile D:\aa\dcm\input.nii; % 输入文件路径subsetSize [10 10 10]; % 截取的图像块大小 subsetStart [1 1 1]; % 截取的…...

JMeter配置原件-计数器
一、面临的问题: 由于本人的【函数助手对话框】中counter计数器每次加2,且只显示偶数(如下图所示),因此借助【配置原件-计数器】来实现计数功能。 如果有大佬知道解决方式,麻烦评论区解答一下,谢谢。 二、配置原件-c…...

go面试问题
1 Go的内存逃逸如何分析 go build -gcflags-m main_pointer.go 2 http状态码 300 请求的资源可包括多个位置,相应可返回一个资源特征与地址的列表用于用户终端(例如:浏览器)选择 301 永久移动。请求的资源已被永久的移动到新U…...
springboot 配置Kafka 关闭自启动连接
这里写自定义目录标题 springboot 配置Kafka 关闭自启动连接方法一:使用 ConditionalOnProperty方法二:手动管理Kafka监听器容器方法三:使用 autoStartupfalse结语 springboot 配置Kafka 关闭自启动连接 在Spring Boot应用程序中,…...

selenium工作原理
原文链接:https://blog.csdn.net/weixin_67603503/article/details/143226557 启动浏览器和绑定端口 当你创建一个 WebDriver 实例(如 webdriver.Chrome())时,Selenium 会启动一个新的浏览器实例,并为其分配一个特定的…...

day14-16系统服务管理和ntp和防火墙
一、自有服务概述 服务是一些特定的进程,自有服务就是系统开机后就自动运行的一些进程,一旦客户发出请求,这些进程就自动为他们提供服务,windows系统中,把这些自动运行的进程,称为"服务" window…...
Hadoop、Hbase使用Snappy压缩
1. 前期准备 系统环境:centos7.9 配置信息:8C8G100G hadoop和hbase为单节点部署模式 jdk版本jdk1.8.0_361 1.1. 修改系统时间 timedatectl set-timezone <TimeZone> 1.2. 修改主机名以及主机名和IP的映射 vim /etc/hosts #将自己的主机名以及…...

【python】OpenCV—Image Moments
文章目录 1、功能描述2、图像矩3、代码实现4、效果展示5、完整代码6、涉及到的库函数cv2.moments 7、参考 1、功能描述 计算图像的矩,以质心为例 2、图像矩 什么叫图像的矩,在数字图像处理中有什么作用? - 谢博琛的回答 - 知乎 https://ww…...

环境变量的知识
目录 1. 环境变量的概念 2. 命令行参数 2.1 2.2 创建 code.c 文件 2.3 对比 ./code 执行和直接 code 执行 2.4 怎么可以不带 ./ 2.4.1 把我们的二进制文件拷贝到 usr/bin 路径下,也不用带 ./ 了 2.4.2 把我们自己的路径添加到环境变量里 3. 认识PATH 3.…...

ATECLOUD测试平台有哪些功能?
测试方案搭建 可视化拖拽编程:采用零代码的图文拖拽形式,用户通过鼠标拖拽节点和连线,即可可视化地构建测试模型,无需懂得代码开发,15 分钟左右就能快速搭建项目,大大降低了上手门槛。 子项目多层嵌套&am…...

使用pyinstaller打包pyqt的程序,运行后提示ModuleNotFoundError: No module named ‘Ui_main‘
环境:windowpython3.9pyqt6 使用pyqt UI编辑器生成了main.ui ,main.ui编译成了Ui_main.py main.py 使用当前目录下的Ui_main.py。 打包过程没报错,运行报错。 错误如下: 解决方法:pyinstaller -Fw main.py --paths. 使…...
搭建分布式Spark集群
title: 搭建分布式Spark集群 date: 2024-11-29 12:00:00 categories: - 服务器 tags: - Spark - 大数据搭建分布式Spark集群 本次实验环境:Centos 7-2009、Hadoop-3.1.4、JDK 8、Zookeeper-3.6.3、scala-2.11.5、Spark-3.2.1 功能规划 MasterSlave1Slave2主节点…...

Django基础 - 01入门简介
一、 基本概念 1.1 Django说明 Django发布于2005年, 网络框架, 用Python编写的开源的Web应用框架。采用了MVC框架模式,也称为MTV模式。官网: https://www.djangoproject.com1.2 MVC框架 Model: 封装和数据库相关…...

简单的bytebuddy学习笔记
简单的bytebuddy学习笔记 此笔记对应b站bytebuddy学习视频进行整理,此为视频地址,此处为具体的练习代码地址 一、简介 ByteBuddy是基于ASM (ow2.io)实现的字节码操作类库。比起ASM,ByteBuddy的API更加简单易用。开发者无需了解class file …...

【服务端】Redis 内存超限问题的深入探讨
在 Java 后端开发中,Redis 内存超限是一个常见的问题,可能由多种原因引起。理解这些原因以及如何处理已经超出限制的数据对于保持系统的稳定性和性能至关重要。 一、Redis 内存超限的原因分析 Redis 是一个高性能的内存键值对存储系统,它在…...
Springboot logback 日志打印配置文件,每个日志文件100M,之后滚动到下一个日志文件,日志保留30天(包含traceid)
全部配置 logback.xml <?xml version"1.0" encoding"UTF-8"?> <configuration debug"false"><property name"LOG_HOME" value"log"/><property name"LOG_NAME" value"admin"/&g…...

《计算机组成及汇编语言原理》阅读笔记:p1-p8
《计算机组成及汇编语言原理》学习第 1 天,p1-p8 总结,总计 8 页。 一、技术总结 1.Intel 8088 microprocessor(微处理器), 1979-1988。 2.MS-DOS Microsoft Disk Operating System的缩写,是一个操作系统(operating system)。…...

基于Flask实现的医疗保险欺诈识别监测模型
基于Flask实现的医疗保险欺诈识别监测模型 项目截图 项目简介 社会医疗保险是国家通过立法形式强制实施,由雇主和个人按一定比例缴纳保险费,建立社会医疗保险基金,支付雇员医疗费用的一种医疗保险制度, 它是促进社会文明和进步的…...

ESP32读取DHT11温湿度数据
芯片:ESP32 环境:Arduino 一、安装DHT11传感器库 红框的库,别安装错了 二、代码 注意,DATA口要连接在D15上 #include "DHT.h" // 包含DHT库#define DHTPIN 15 // 定义DHT11数据引脚连接到ESP32的GPIO15 #define D…...
【ROS】Nav2源码之nav2_behavior_tree-行为树节点列表
1、行为树节点分类 在 Nav2(Navigation2)的行为树框架中,行为树节点插件按照功能分为 Action(动作节点)、Condition(条件节点)、Control(控制节点) 和 Decorator(装饰节点) 四类。 1.1 动作节点 Action 执行具体的机器人操作或任务,直接与硬件、传感器或外部系统…...
GitHub 趋势日报 (2025年06月08日)
📊 由 TrendForge 系统生成 | 🌐 https://trendforge.devlive.org/ 🌐 本日报中的项目描述已自动翻译为中文 📈 今日获星趋势图 今日获星趋势图 884 cognee 566 dify 414 HumanSystemOptimization 414 omni-tools 321 note-gen …...

Map相关知识
数据结构 二叉树 二叉树,顾名思义,每个节点最多有两个“叉”,也就是两个子节点,分别是左子 节点和右子节点。不过,二叉树并不要求每个节点都有两个子节点,有的节点只 有左子节点,有的节点只有…...

dify打造数据可视化图表
一、概述 在日常工作和学习中,我们经常需要和数据打交道。无论是分析报告、项目展示,还是简单的数据洞察,一个清晰直观的图表,往往能胜过千言万语。 一款能让数据可视化变得超级简单的 MCP Server,由蚂蚁集团 AntV 团队…...

算法笔记2
1.字符串拼接最好用StringBuilder,不用String 2.创建List<>类型的数组并创建内存 List arr[] new ArrayList[26]; Arrays.setAll(arr, i -> new ArrayList<>()); 3.去掉首尾空格...

并发编程 - go版
1.并发编程基础概念 进程和线程 A. 进程是程序在操作系统中的一次执行过程,系统进行资源分配和调度的一个独立单位。B. 线程是进程的一个执行实体,是CPU调度和分派的基本单位,它是比进程更小的能独立运行的基本单位。C.一个进程可以创建和撤销多个线程;同一个进程中…...
怎么让Comfyui导出的图像不包含工作流信息,
为了数据安全,让Comfyui导出的图像不包含工作流信息,导出的图像就不会拖到comfyui中加载出来工作流。 ComfyUI的目录下node.py 直接移除 pnginfo(推荐) 在 save_images 方法中,删除或注释掉所有与 metadata …...

渗透实战PortSwigger靶场:lab13存储型DOM XSS详解
进来是需要留言的,先用做简单的 html 标签测试 发现面的</h1>不见了 数据包中找到了一个loadCommentsWithVulnerableEscapeHtml.js 他是把用户输入的<>进行 html 编码,输入的<>当成字符串处理回显到页面中,看来只是把用户输…...