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 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.

121, 123题的延伸版本,123题是只交易2次,本题是交易k次

思路:
虽然整体思路和123题一样,但是不能直接那样做,因为在k很大的时候,比如k=100亿次,这时候声明的dp数组会超出内存,所以需要在123题的基础上做一些优化

需要知道的是一次有收益的交易最少是需要2天完成的,当天买当天卖肯定没有收益。
那么就算是不停地交易,当天买第二天就卖掉,也只需要prices.length/2次

所以当k>=prices.length/2时,不需要真的计算k次,只需要用贪心法算出最大的收益
就是每当第二天价格>当天价格的时候就加到收益里面,直接返回最大收益

然后k < prices.length/2时,就按照123题的dp来做:
第 i 次交易时, j 时刻如果选择不交易,收益是保持第i次,j-1时刻的收益,也就是dp[i][j - 1]

如果选择在j时刻卖掉,因为买入可以是从0到j-1的任何一个,设m=0~j-1
那么收益就是第i-1次交易时,m时刻的收益,减去买入m时刻的价格,加上现在在j时刻卖掉的价格,即
dp[i-1][m] - prices[m] + prices[j], for m = 0~ j - 1
要在m=0~j-1中取最大收益
max(dp[i-1][m] - prices[m] ) + prices[j], for m = 0~ j - 1

不需要在每个j时都遍历0~j-1,只需要保持实时更新最大差值即可

要在交易和不交易两种情况中取较大的值
dp[i][j] = max(dp[i][j - 1], max_diff + prices[j])

    int maxProfit(int k, vector<int>& prices) {
        if (k == 0 || prices.size() == 0) {
            return 0;
        }
        
        int max_profit = 0;
        
        if (k >= prices.size()/2) {
            for (int i = 1; i < prices.size(); i++) {
                if (prices[i] > prices[i - 1]) {
                    max_profit += (prices[i] - prices[i - 1]);
                }
            }
            return max_profit;
        }
        
        vector<vector<int>> dp(k + 1, vector<int>(prices.size(), 0)); 
        
        for (int i = 1; i <= k; i++) {
            int max_diff = -prices[0];
            for (int j = 1; j < prices.size(); j++) {
                dp[i][j] = max(dp[i][j - 1], max_diff + prices[j]);
                max_diff = max(max_diff, dp[i - 1][j] - prices[j]);
            }
        }
        
        return dp[k][prices.size() - 1];
    }

java版本

    public int maxProfit(int k, int[] prices) {
        if(k == 0 || prices.length == 0) {
            return 0;
        }
        
        int n = prices.length;
        //int[][] dp = new int[k+1][n]; //写在这里会MLE
        int result = 0;
        
        //k >= n/2时为greedy
        if(k >= n/2) {
            for(int i = 1; i < n; i++) {
                int val = prices[i] - prices[i - 1];
                if(val > 0) {
                    result += val;
                }
            }
            return result;
        }
        
        int[][] dp = new int[k+1][n];
        //ith transaction:max profit in 0~m, buy at m, sell at j,m:0~j-1
        //for m: dp[i][j] = max(dp[i-1][m] - prices[m]) + prices[j]
        //dp[i][j]:第i次transaction,在j时间点处的profit
        //不交易时保持在第i次transaction,j-1时间点处的profit(第i行必须是第i次transaction)
        for(int i = 1; i <= k; i++) {
            int maxDiff = -prices[0];
            for(int j = 1; j < n; j++) {
                dp[i][j] = Math.max(dp[i][j-1], maxDiff + prices[j]);
                maxDiff = Math.max(maxDiff, dp[i-1][j] - prices[j]);
            }
        }
        
        return dp[k][n-1];
    }
高速电路设计必看:同步开关噪声问题解析 数字电路中的同步开关噪声(SSN)问题日益突出,尤其是随着高速器件应用增多。本文分析了地弹和电压弹的产生机理,指出其与电源网络电感、输出驱动电流变化率密切相关。文章详细阐述了地弹参数特征,包括峰值电压、脉冲宽度等关键指标,并探讨了负载电容、信号压摆率等因素对地弹的影响。最后提出系统化的解决方案,涵盖芯片选型、电路设计、PCB布局和后期调试等多个环节,强调通过降低回路电感和控制电流变化率来有效抑制SSN。这些措施需要在性能、成本和复杂度之间取得平衡,为高速数字电路设计提供了重要参考。 阅读详情

相关推荐

PX4 Gazebo仿真进阶:自定义飞机模型和地图的完整指南

本文详细介绍了如何在PX4 Gazebo仿真中自定义飞机模型和地图模型,包括文件架构解析、参数调整指南、地图定制技巧及常见问题解决方案。通过实战步骤和性能优化建议,帮助开发者高效完成复杂场景的飞行控制算法测试。

weixin_29081101的博客 386

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

LeetCode:188. Best Time to Buy and Sell Stock IV(买卖股票的最佳时机 )问题描述:给定一个数组,它的第i个元素是一支给定的股票在第i天的价格。设计一个算法来计算你所能获取的最大利润。你最多可以完成k笔交易。 注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。示例1:输入: [2,4,1], k = 2 输出: 2...

Growth Diary 2179

Windows下用Caddy一键搞定LiveKit本地HTTPS部署(含自签名证书避坑指南)

本文详细介绍了在Windows本地开发环境中,如何利用Caddy服务器一键部署支持HTTPS和WSS的LiveKit实时通信服务。文章重点解决了自签名证书的生成与配置难题,提供了完整的避坑指南和防火墙设置,帮助开发者快速搭建安全的WebRTC测试环境,实现局域网内的实时音视频互动。

weixin_29274969的博客 584

leetcode 第188题,我的解法,Best Time to Buy and Sell Stock IV

leetcode第188题,Best Time to Buy and Sell Stock IV题目如下: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/ 使用了最大堆

郭腾虎的专栏 628

大数据工程中的数据血缘分析工具比较

数据血缘(Data Lineage)是大数据治理中的核心组成部分,它描述了数据从源头到目标的完整流动路径。系统介绍数据血缘的核心概念和技术原理比较主流开源和商业数据血缘工具的功能特点提供数据血缘分析的实践指南和选型建议本文首先介绍数据血缘的基本概念,然后深入分析其技术原理和实现方法,接着比较主流工具的特点,最后通过实际案例展示应用场景。数据血缘(Data Lineage): 描述数据从源头到目标的完整流动路径,包括所有转换和处理步骤元数据(Metadata)

大数据洞察的博客 900

ArcGIS与地理加权回归GWR【一】

因此,在实际问题研究中我们经常发现回归参数在不同地理位置上往往表现为不同,也就是说回归参数随地理位置变化,这时如果仍然采用全局空间回归模型(全局假设β是不会变得),得到的回归参数估计将是回归参数在整个研究区域内的平均值,如上所说某一个因素在ABC等不同的地理位置对房价的影响是不同的,假如采用全局空间回归模型,便忽略了数据的空间位置属性,只反映平均意义下因变量与自变量的相关关系,而不能有效反映回归关系的空间非平稳性的特征。当自变量为1个时,是一元线性回归,自变量为2个及以上时,称为多元线性回归。

JData_Engineer的博客 1376

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

基于深度学习的树木种类识别

本文介绍了基于深度学习的树木种类识别技术。我们将通过深度学习模型和图像处理技术实现对树木的自动识别与分类。首先,我们将介绍深度学习的基本原理和相关算法。接着,我们将详细说明树木种类识别的数据准备、模型构建和训练过程。最后,我们将给出代码示例,帮助读者深入了解和实践该技术。

一键难忘的博客 2319

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

LeetCode解题 188:Best Time to Buy and Sell Stock IV (动态规划)Problem 188: Best Time to Buy and Sell Stock IV [Hard]解题思路Solution (Java)修改过程 Problem 188: Best Time to Buy and Sell Stock IV [Hard] Say you hav...

Fayedily的博客 596

车载网络测试实操源码_使用CAPL解析VBF文件

VBF(Versatile Binary Format)文件是一种二进制文件格式,被沃尔沃、福特、马自达、吉利等汽车制造商广泛采用。这种格式无法使用我们常规的烧录器进行刷写,通常需要进行解析转化。如果各位需要自己编写软件或脚本来刷写VBF文件,或者需要对刷写功能进行测试时,那么本篇文章就会对你非常有用。今天我们就来讲一下如何使用CAPL脚本对VBF文件进行数据解析。VBF文件包含三部分:VBF版本段、文件头段、数据段。前面的版本段和文件头段是ASCII码,包含版本、地址、校验码等信息

文章主要涉及嵌入式软件开发、测试、项目管理等,欢迎交流,共同进步。 3005

Python爬虫教程:如何爬取多平台电商商品信息(价格、评价、库存)

本文介绍了如何编写一个跨平台电商商品爬虫,爬取多个平台的商品信息,包括商品名称、价格、评价等数据。通过Python的爬虫库(如requestsSelenium)和数据处理库(如pandasmatplotlib)的结合,我们可以高效地获取和分析电商平台上的商品信息。

2201_76125261的博客 920

LeetCode(188) Best Time to Buy and Sell Stock IV (Java)

题目如下: Best Time to Buy and Sell Stock Total Accepted: 43912 Total Submissions: 135635 My Submissions Question Solution  Say you have an array for which the ith element is the price of a given stock

BUILD 7494

博途PLC如何建立与笔记本电脑端的连接?(新手必会)

对S7-1500PLC下载硬件组态或程序,需要建立PC与PLC的连接。 由于S7-1500CPU都具有PN端口,因此建立PC与S7-1500PLC的连接通常使用工业以太网来实现。 1.使用网线连接PC-PLC 使用网线,一端连接PC的以太网卡端口,另一端连接S7-1500CPU的PN端口。 2.设置本机IP地址 2.1 确认本机要设置的IP地址段 本机IP地址要和PLC程序组态IP地址段前三位保持一致,后一位使用组态中没有用到的IP地址段。如下图所示。 那么看了这个图片应该就知道了,地址应该设置成192.

weixin_42430971的博客 1万+

LeetCode //C - 188. Best Time to Buy and Sell Stock IV

【代码】LeetCode //C - 188. Best Time to Buy and Sell Stock IV。

Made in Code 1152

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

Devexpress16.2.6破解工具

Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具Devexpress16.2.6破解工具

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

James Pan 2086

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

LeetCode188 Best Time to Buy and Sell Stock IV

Say you have an array for which theithelement is the price of a given stock on dayi. Design an algorithm to find the maximum profit. You may complete at mostktransactions. Note: You may not enga...

李歇特冯-兹拜因巴哈的博客 216

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

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

题目来源:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/ 问题描述 188.Best Time to Buy and Sell Stock IV Hard Say you have an array for which theithelement is the price of a given stoc...

da_kao_la的博客 1733

LeetCode 188. Best Time to Buy and Sell Stock IV

最多转k次 求最大利润 毫无思路 不妨来看之前的笔记: 利用二维DP去做 dp[i][j] is defined as maximum profit from at most i transactions using prices[0…j] so what’s the transaction formula? so on day j, we have two options: do nothing, that makes dp[i][j] = dp[i][j-1] or we choose to sell

Tech in Pieces 426

LeetCode 188. Best Time to Buy and Sell Stock IV - 三维DP详解

题意 + 思路一句话概括:这是「最多进行 k 次交易」的股票买卖问题,可以用三维 DP:dp[day][transaction][hold]dp[day][transaction][hold]dp[day][transaction][hold],其中交易数按「卖出次数」计数,买入不加 1,卖出才加 1。​。

六六哥的博客 933

[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

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 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 may complete at most k transactions. Note: You may not

coder 进阶的专栏 1017

leetcode 188 Best Time to Buy and Sell Stock IV

Say you have an array for which theithelement is the price of a given stock on dayi. Design an algorithm to find the maximum profit. You may complete at mostktransactions. Note: You may not eng...

cmy203的博客 177

【Leetcode】188. Best Time to Buy and Sell Stock IV

题目地址: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/ 给定每天的股票价格,以数组ppp的形式给出,每天只能做一次交易并且每次只能买一股,问如果只允许做最多kkk次买卖,那么最大收益是多少。 不妨设ppp的长度为nnn。首先,如果k≥n/2k\ge n/2k≥n/2,那么就相当于可以买卖无限次,因为买入和卖出的总次数小于等于nnn。而买卖无限次是很容易的,只需要将每次股票上涨的差价都赚到即可。接下来考虑k<n/2k

数学、算法爱好者的博客 280

[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 [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.

贫道绝缘子的博客 234
上一篇: leetcode 213. House Robber II
下一篇: leetcode 139. Word Break
蓝羽飞鸟
博客等级 码龄8年 1万+粉丝 727原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值