【LeetCode】解题188:Best Time to Buy and Sell Stock IV(动态规划)

LeetCode第188题解析 给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 示例1: 输入: [2,4,1], k = 2 输出: 2 解释: 在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 = 4-2 = 2 。 示例 2: 输入: [3,2,6,5,0,3], k = 2 输... 阅读详情

LeetCode解题 188:Best Time to Buy and Sell Stock IV (动态规划)

Problem 188: Best Time to Buy and Sell Stock IV [Hard]

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most k transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Example 1:

Input: [2,4,1], k = 2
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.

Example 2:

Input: [3,2,6,5,0,3], k = 2
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4.
Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.

来源:LeetCode

解题思路

本题需要使用动态规划思想。与题解123:Best Time to Buy and Sell Stock III同属于最佳时机买卖股票问题。

解题思路选用[题解123]中的方法III,123题中是最多可以交易2次,复杂度为 O ( n ) O(n) O(n)时间+ O ( 4 ) O(4) O(4)空间,本题中最多可以交易k次,所以复杂度为 O ( n ) O(n) O(n)时间+ O ( 2 k ) O(2k) O(2k)空间。
在一次循环中,可以使用k组{minCostj, maxPj},先计算第一轮的{minCost1, maxP1},再计算第二轮的{minCost2, maxP2},…,最后计算第k轮的{minCostk, maxPk}。

更新公式为:
c p c p 0 = [ p r i c e s [ 0 ] 0 p r i c e s [ 0 ] 0 . . . p r i c e s [ 0 ] 0 ] cpcp_0 = \begin{bmatrix} prices[0] \\ 0 \\ prices[0] \\ 0 \\ ... \\ prices[0] \\ 0 \end{bmatrix} \\ cpcp0​=⎣⎢⎢⎢⎢⎢⎢⎢⎢⎡​prices[0]0prices[0]0...prices[0]0​⎦⎥⎥⎥⎥⎥⎥⎥⎥⎤​
c p c p = [ { min ⁡ { c p c p [ 0 ] , p r i c e s [ i ] } max ⁡ { c p c p [ 1 ] , p r i c e s [ i ] − c p c p [ 0 ] } . . . min ⁡ { c p c p [ 2 ∗ j ] , p r i c e s [ i ] − c p c p [ 2 ∗ j − 1 ] } max ⁡ { c p c p [ 2 ∗ j + 1 ] , p r i c e s [ i ] − c p c p [ 2 ∗ j ] } . . . min ⁡ { c p c p [ 2 ∗ k − 2 ] , p r i c e s [ i ] − c p c p [ 2 ∗ k − 3 ] } max ⁡ { c p c p [ 2 ∗ k − 1 ] , p r i c e s [ i ] − c p c p [ 2 ∗ k − 2 ] } ] , i ∈ [ 0 , N − 1 ] , j ∈ [ 0 , k − 1 ] cpcp = \begin{bmatrix} \{\min\{cpcp[0], prices[i]\} \\ \max\{cpcp[1], prices[i]-cpcp[0]\} \\ ... \\ \min\{cpcp[2*j], prices[i] - cpcp[2*j-1]\} \\ \max\{cpcp[2*j+1], prices[i] - cpcp[2*j]\} \\ ... \\ \min\{cpcp[2*k-2], prices[i] - cpcp[2*k-3]\} \\ \max\{cpcp[2*k-1], prices[i] - cpcp[2*k-2]\} \end{bmatrix}, i\in[0, N-1], j\in[0, k-1] cpcp=⎣⎢⎢⎢⎢⎢⎢⎢⎢⎢⎢⎡​{min{cpcp[0],prices[i]}max{cpcp[1],prices[i]−cpcp[0]}...min{cpcp[2∗j],prices[i]−cpcp[2∗j−1]}max{cpcp[2∗j+1],prices[i]−cpcp[2∗j]}...min{cpcp[2∗k−2],prices[i]−cpcp[2∗k−3]}max{cpcp[2∗k−1],prices[i]−cpcp[2∗k−2]}​⎦⎥⎥⎥⎥⎥⎥⎥⎥⎥⎥⎤​,i∈[0,N−1],j∈[0,k−1]
其中 N N N为总天数, k k k为最大交易次数。
c p c p = { m i n C o s t 1 , m a x P 1 , . . . , m i n C o s t j + 1 , m a x P j + 1 , . . . , m i n C o s t k , m a x P k } cpcp = \{minCost_1, maxP_1, ...,minCost_{j+1}, maxP_{j+1},...,minCost_k, maxP_k\} cpcp={minCost1​,maxP1​,...,minCostj+1​,maxPj+1​,...,minCostk​,maxPk​},更新过程相当于
c p c p = [ m i n C o s t 1 = min ⁡ { m i n C o s t 1 , p r i c e s [ i ] } m a x P 1 = max ⁡ { m a x P 1 , p r i c e s [ i ] − m i n C o s t 1 } . . . m i n C o s t j + 1 = min ⁡ { m i n C o s t j + 1 , p r i c e s [ i ] − m a x P j } m a x P j + 1 = max ⁡ { m a x P j + 1 , p r i c e s [ i ] − m i n C o s t j + 1 } . . . m i n C o s t k = min ⁡ { m i n C o s t k , p r i c e s [ i ] − m a x P k − 1 } m a x P k = max ⁡ { m a x P k , p r i c e s [ i ] − m i n C o s t k } ] cpcp = \begin{bmatrix} minCost_1 = \min\{minCost_1,prices[i]\} \\ maxP_1 = \max\{maxP_1,prices[i]-minCost_1\} \\ ... \\ minCost_{j+1} = \min\{minCost_{j+1},prices[i]-maxP_j\} \\ maxP_{j+1} = \max\{maxP_{j+1}, prices[i]-minCost_{j+1}\} \\ ... \\ minCost_k = \min\{minCost_k,prices[i]-maxP_{k-1}\} \\ maxP_k = \max\{maxP_k,prices[i]-minCost_k\} \end{bmatrix} cpcp=⎣⎢⎢⎢⎢⎢⎢⎢⎢⎢⎢⎡​minCost1​=min{minCost1​,prices[i]}maxP1​=max{maxP1​,prices[i]−minCost1​}...minCostj+1​=min{minCostj+1​,prices[i]−maxPj​}maxPj+1​=max{maxPj+1​,prices[i]−minCostj+1​}...minCostk​=min{minCostk​,prices[i]−maxPk−1​}maxPk​=max{maxPk​,prices[i]−minCostk​}​⎦⎥⎥⎥⎥⎥⎥⎥⎥⎥⎥⎤​
该方法只需要 O ( n ) O(n) O(n)时间, O ( 2 k ) O(2k) O(2k)空间。

注意:当k非常大时,会出现超出内存限制的问题,此时需要将 k > N 2 k > \frac{N}{2} k>2N​的情况分开考虑。由于一次交易至少需要两天,所以当 k > N 2 k > \frac{N}{2} k>2N​时,实际上相当于交易次数不受限制,也就是题解122:Best Time to Buy and Sell Stock II中的题意,可以复用该题的代码。

运行结果:
在这里插入图片描述
要点:动态规划

Solution (Java)

O(n)时间+O(2k)空间

class Solution {
    public int maxProfit(int k, int[] prices) {
        int N = prices.length;
        if(k < 1 || N < 2) return 0;
        if(k > N/2) return nolimit(prices);
        int[] cpcp = new int[2*k];
        for(int j = 0; j < k; j++){
            cpcp[2*j] = prices[0];
            cpcp[2*j+1] = 0;
        }
        for(int i = 1; i < N; i++){
            cpcp[0] = Math.min(cpcp[0], prices[i]);
            cpcp[1] = Math.max(cpcp[1], prices[i] - cpcp[0]);
            for(int j = 1; j < k; j++){
                cpcp[2*j] = Math.min(cpcp[2*j], prices[i] - cpcp[2*j-1]);
                cpcp[2*j+1] = Math.max(cpcp[2*j+1], prices[i] - cpcp[2*j]);
            }
        }
        return cpcp[2*k-1];
    }
    private int nolimit(int[] prices){
        int maxP = 0;
        for(int i = 1; i < prices.length; i++){
            maxP += Math.max(0, prices[i] - prices[i-1]);
        }
        return maxP;
    }
}

修改过程

  • 样例输入k=1000000000时,出现超出内存限制问题,需要将其考虑为无限次交易的情况,因此添加函数nolimit()。
深入掌握英飞凌TriCore中断向量表 摘要:本文探讨了英飞凌Tc277芯片中断机制的原理与实现,重点解析了中断向量表基地址的链接文件定义方式、BIV寄存器的初始化过程以及每个中断条目的32字节空间分配规则。通过分析中断向量号(1-255)的计算方法,阐明了中断条目跳转地址(如STM0中断向量号37对应0x800F04A0)的生成逻辑。文章还揭示了.map文件中14字节跳转指令的组成原理,以及最终通过a14寄存器跳转到实际中断函数(如stm0Sr0ISR)的执行流程,为嵌入式开发人员理解中断处理机制提供了清晰的技术路径。 阅读详情

相关推荐

告别‘线束丛林’:手把手拆解车身域控制器(BCM/PEPS/网关)的硬件选型与PCB布局要点

本文深入解析车身域控制器的硬件选型与PCB布局要点,涵盖主控MCU选择、通信接口设计、电源架构优化及EMC设计等关键环节。通过实战案例分享,帮助工程师解决高密度集成带来的电源完整性、热管理和信号隔离挑战,实现更稳定高效的汽车电子系统设计。

weixin_42567279的博客 394

leetcode:188. 买卖股票的最佳时机 IV(最多买卖k次)

首先我们来确定一天会有几个状态,最容易想到的有四种:这是四种大家最容易想到的状态, 但是同时操作四个状态确实有点复杂了, 通过分析后我们可以将状态优化为两个状态:当天持有股票和当天不持有股票。每个状态又是由两种情况组合而成,本质上还是四个状态, 只不过通过优化后我们就只需要操作两个状态了.。下面我们考虑如何表示这两个状态。最终的步骤是确定dp数组有几个维度。所以最终就得到了两个二维的dp数组定义如下图: 在确定递推公式时, 我们必须先明确一个概念:k何时进行变化。这点很重要, 直接就导致之后递推公式的不同.

OceanStar的博客 1098

CiteSpace关键词聚类图谱含义详细解析

CiteSpace关键词聚类图谱含义详细解析 回顾上一次推文:CiteSpace关键词共现图谱含义详细解析 其中有一句: 当你人工已经可以很容易的进行归纳后,就不需要再利用CiteSpace聚类功能啦。 我们来看一下上次推文做出来的关键词共现图谱: 人工不好归纳!那怎么聚类呢? 此时便可使用CiteSpace的聚类功能啦! 如下所示:我们可以清晰地看到上边的关键词共现网络聚成了一个个不规则区域...

qq_39974284的博客 6万+

[LeetCode] 188、买卖股票的最佳时机 IV

题目描述 给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。 输入: [3,2,6,5,0,3], k = 2 输出: 7 解释: 在第 2 天 (股票价格 = 2) 的时候买入,在第 3 天 (股票价格 = 6) 的时候卖出, 这笔交易所能获得利润 = 6-2 = 4 。 随后,在第 5 天 (股票价...

aift的专栏 553

交流电路计算方法:复阻抗和相量法

一,复阻抗 电容电路,电压与电流的大小比值是XC=1/WC,相位上电流比电压超前90度 这样描述很麻烦,在复平面里,相位超前90度,可以用什么数学表示呢? 也就是说,一个相量,乘以j之后,大小没变化,相位变得超前90度了 同样的,大小不变,相位落后90度应该除以j 原来我们说电容电路,给个电压,算电流又要算XC,又要另外说相位超前90度,现在可以简单点 在这个计算式里,1/wc还是原来的容抗大...

theory and practice的博客 3万+

RFSOC实战解析(一):深入RF Data Converter的时钟与数据接口设计

本文深入解析RFSOC中RF Data Converter的时钟与数据接口设计,涵盖GHz采样、数据流处理、时钟树同步及AXI-Stream接口实战。通过详细案例和调试技巧,帮助工程师高效配置IP核,优化ADC/DAC性能,解决跨时钟域和信号完整性等关键问题。

weixin_30955617的博客 473

LeetCode第188题--买卖股票的最佳时机 IV

给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。 注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 示例 1: 输入: [2,4,1], k = 2 输出: 2 解释: 在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 ...

king3wade的博客 249

vscode中创建vue快捷键

1.安装Vetur插件(扩展里面直接搜) 2.vscode 界面里面左上角选则 文件=> 首选项=> 用户代码片段=>新建全局代码片段=>在输入框中新建名称为vue.json 3.删除里面的注释,当然你也可以留着,把下面的代码粘贴进去! { // Place your 全局 snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and // descri

Leon_940002463的博客 3207

【LeetCode】动态规划—188. 买卖股票的最佳时机 IV(附完整Python/C++代码)

买卖股票的最佳时机 IV 是股票交易系列问题中的一个变种,难度较高。该问题要求我们最多进行 k 次交易,每次交易包含一次买入和一次卖出,目标是通过这 k 次交易获取最大利润。该问题结合了 动态规划 和 贪心 的思想,要求我们合理规划每次买卖的时机以获取最大利润。

Albert_Lsk的博客 1782

全志V3S开发板实战:从零构建嵌入式Linux系统

本文提供了一份针对全志V3S开发板(如LicheePi Zero)的零基础教程,详细指导如何从零开始构建嵌入式Linux系统。内容涵盖编译环境搭建、交叉工具链配置、U-Boot引导程序编译与烧录、Linux内核定制与编译,以及使用Buildroot构建根文件系统,最终实现系统成功启动,帮助开发者深入理解嵌入式系统构建全流程。

tensor9flow的博客 574

京东/淘宝商品评论情感分析:基于Python的大规模评论爬取与NLP情感分析实战

在当今电商蓬勃发展的时代,用户评论已成为影响消费者购买决策的关键因素。本文将详细介绍如何使用Python最新技术栈爬取京东和淘宝商品评论,并运用先进的自然语言处理技术对评论进行情感分析,识别用户的好评与差评倾向。通过完整的代码实现和深入的技术解析,帮助读者掌握从数据采集到情感分析的全流程。本文详细介绍了如何使用Python最新技术栈实现京东和淘宝商品评论的爬取与情感分析。通过结合异步爬虫、反爬策略、BERT情感分析等先进技术,我们构建了一个完整的评论分析系统。高效爬取。

2201_76125261的博客 1402

LeetCode: 188. Best Time to Buy and Sell Stock IV

LeetCode: 188. Best Time to Buy and Sell Stock IV 题目描述 Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You ma...

杨领well的专栏 507

【绝对要收藏-优秀论文范文】高项-度量绩效域

摘要:本文基于某水库数字孪生平台建设项目(2022.9-2023.5,645.97万元)的管理实践,从信息系统度量绩效域角度展开论述。项目构建了包含防洪调度等6大子系统的数字平台,实现洪水"四预"功能。重点分析了度量绩效域的五大要点:制定有效指标(如成本±8%偏差阈值)、多维数据采集、预警临界值设定、基于趋势的主动干预和持续改进机制。特别阐述了绩效问题的诊断方法,包括设备采购全周期成本分析、阶段性成本报告制度等。项目状态展示采用三维可视化看板,集成进度、成本、质量等多维度实时数据,最终实

xylllamm的博客 344

【LeetCode】解题309:Best Time to Buy and Sell Stock with Cooldown(动态规划)

LeetCode解题 309:Best Time to Buy and Sell Stock with Cooldown (动态规划)Problem 309: Best Time to Buy and Sell Stock with Cooldown [Medium]解题思路Solution (Java)修改过程 Problem 309: Best Time to Buy and Sell Sto...

Fayedily的博客 323

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

Leetcode 188 Best Time to Buy and Sell Stock IV 至多k次买卖股票最大收益

假设你有一个数组,里面记录的是每一天的股票的价格。设计一个算法来计算最大收益。你至多可以完成k次交易。你不能同时进行多次交易(即,在你买入股票之前必须卖掉手里的股票)。

(ง •̀_•́)ง 2024

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

[LeetCode] Best Time to Buy and Sell Stock IV

Say you have an array for which the ithi^{th} element is the price of a given stock on day ii.Design an algorithm to find the maximum profit. You may complete at most k transactions.Note: You may not

楚兴 1万+

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

[leetcode] 188. Best Time to Buy and Sell Stock IV 解题报告

题目链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/ Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the m

小榕流光的专栏 3365

【LeetCode】188. Best Time to Buy and Sell Stock IV 解题报告(Python)

作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录题目描述题目大意解题方法日期 题目地址:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/description/ 题目描述 Say you have an array for which the it...

负雪明烛 3949

LeetCode-188. Best Time to Buy and Sell Stock IV [C++][Java]

You are given an integer arraypriceswhereprices[i]is the price of a given stock on theithday, and an integerk. Find the maximum profit you can achieve. You may complete at mostktransactions.

贫道绝缘子的博客 232

[LeetCode] 188. Best Time to Buy and Sell Stock IV

原题链接: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/ Buy and Sell Stock专题相关题目 121. Best Time to Buy and Sell Stock 122. Best Time to Buy and Sell Stock II 123. Best Time to Buy and ...

Ber03的博客 233

【LeetCode】188. Best Time to Buy and Sell Stock IV 买卖股票的最佳时机 IV(Hard)(JAVA)每日一题

【LeetCode】188. Best Time to Buy and Sell Stock IV 买卖股票的最佳时机 IV(Hard)(JAVA) 题目地址: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/ 题目描述: You are given an integer array prices where prices[i] is the price of a given stock on the i-

qq_16927853的博客 255

188 Best Time to Buy and Sell Stock IV [Leetcode]

题目内容: Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most k transactions. Note: You m

miranda 447

[LeetCode] 123. Best Time to Buy and Sell Stock III

原题链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ 1. 题目简介 Say you have an array for which the i th element is the price of a given stock on day i. Design an algorithm to find the...

Ber03的博客 292

leetcode188. Best Time to Buy and Sell Stock IV(买卖股票的最佳时机 IV)

题目要求 给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。 注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-...

爱喝舒化奶的博客 400

[LeetCode] 121. Best Time to Buy and Sell Stock

原题链接: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 1. 题目介绍 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 compl...

Ber03的博客 262

LeetCode—188. 买卖股票的最佳时机 IV(Best Time to Buy and Sell Stock IV)——分析及代码(Java)

LeetCode—188. 买卖股票的最佳时机 IV[Best Time to Buy and Sell Stock IV]——分析及代码[Java]一、题目二、分析及代码1. 动态规划(1)思路(2)代码(3)结果三、其他 一、题目 给定一个整数数组 prices ,它的第 i 个元素 prices[i] 是一支给定的股票在第 i 天的价格。 设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。 示例 1: 输入:k =

江南土豆的博客 253
上一篇: 【LeetCode】解题123:Best Time to Buy and Sell Stock III(动态规划)
下一篇: 【LeetCode】解题309:Best Time to Buy and Sell Stock with Cooldown(动态规划)
Fayedy
博客等级 码龄11年 2粉丝 57原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值