LeetCode --Best Time to Buy and Sell Stock III

BioJava(Java Library)指南 Biojava: One bioinformatics java programming library 立即下载

LeetCode –Best Time to Buy and Sell Stock III

技术与社会生态的相互作用,使得技术发展经常带来更深远的问题,远远超出了技术设备的直接目的和运作本身,同样的技术,引入不同的环境,或在不同条件下,会带来非常不同的结果


题目描述

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

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

至多交易2次,求最大利益。

算法解释

  1. basically we want to maximize the formula: -price1 + price2 - price3 + price4, where every price appear in that order. So every time we visit a new price, we update the max possible value of 4 (partial) formula. That’s why we use max for each of the 4 states.
    也就是状态机4个状态。和cooldown相似。

在每个步骤中,我们可以看到,oneBuy始终是输入数组中的最低价格,oneBuyOneSell跟踪价格和最低价格之间的最大差异,TwoBuy的价值变化反映了输入价格数组中的谷底。
变量TwoBuyTwoSell保持直到目前的价格的最大的利润,
(代码比较清晰易懂,请看代码)

  1. DP

f[k, ii] represents the max profit up until prices[ii] (Note: NOT ending with prices[ii]) using at most k transactions.


f[k, ii] = max(f[k, ii-1], prices[ii] - prices[jj] + f[k-1, jj]) { jj in range of [0, ii-1] }
= max(f[k, ii-1], prices[ii] + max(f[k-1, jj] - prices[jj]))

      f[0, ii] = 0; 0 times transation makes 0 profit
      f[k, 0] = 0; if there is only one price data point you can't make any money no matter how many times you can trade

状态转移方程明了了,解释略

代码

public int maxProfit(int[] prices) {
    int oneBuy = Integer.MIN_VALUE;
    int oneBuyOneSell = 0;
    int twoBuy = Integer.MIN_VALUE;
    int twoBuyTwoSell = 0;
    for(int i = 0; i < prices.length; i++){
        oneBuy = Math.max(oneBuy, -prices[i]);//we set prices to negative, so the calculation of profit will be convenient
        oneBuyOneSell = Math.max(oneBuyOneSell, prices[i] + oneBuy);
        twoBuy = Math.max(twoBuy, oneBuyOneSell - prices[i]);//we can buy the second only after first is sold
        twoBuyTwoSell = Math.max(twoBuyTwoSell, twoBuy + prices[i]);
    }

    return Math.max(oneBuyOneSell, twoBuyTwoSell);
}

使用DP的方法

class Solution {
public:
    int maxProfit(vector<int> &prices) {

        if (prices.size() <= 1) return 0;
        else {
            int K = 2; // number of max transation allowed
            int maxProf = 0;
            vector<vector<int>> f(K+1, vector<int>(prices.size(), 0));
            for (int kk = 1; kk <= K; kk++) {
                int tmpMax = f[kk-1][0] - prices[0];
                for (int ii = 1; ii < prices.size(); ii++) {
                    f[kk][ii] = max(f[kk][ii-1], prices[ii] + tmpMax);
                    tmpMax = max(tmpMax, f[kk-1][ii] - prices[ii]);
                    maxProf = max(f[kk][ii], maxProf);
                }
            }
            return maxProf;
        }
    }
};
声音特征提取--Demon谱分析(舰船水声) 不同频带的DEMON谱线相互之间也不一样,有的频带内会发生线谱遗失,有的频带内的线谱并不是真正的谱线。当舰船航速达到某个极限时,螺旋桨的高速旋转将产生空化噪声,由螺旋桨产生的一系列周期信号被空化噪声调制,在频域上表现为将低频的离散线谱线性搬移到较高频率噪声所处的频率周围,这些周期信号在频域是离散的线谱系列,对应舰船的轴频、叶频以及谐波频率,由于舰船辐射噪声低频部分还有其它噪声源,很难从低频段直接提取出螺旋桨产生的线谱系列,而是要先对高频段的调制信号进行解调,通过低通滤波得到信号的低频包络谱,即。 阅读详情

相关推荐

速腾聚创激光雷达复现FAST-LIO

记录复现FAST-LIO算法的过程和,代码梳理和理解。FAST-LIO的简化版、注释版。速腾激光雷达

abanchao的博客 2928

Metasploit - auxiliary/gather/zoomeye_search

How to use ZoomEye API ?If you are a python developer, please view ZoomEye-SDK. If not, ZoomEye API Documentation is good for you.$ sudo easy_install zoomeye-SDKor$ sudo pip install git+https://github.

Nixawk 59万+

国产信创服务器软硬件兼容情况1 --- ARM架构

信创,即信息技术应用创新产业,它是数据安全、网络安全的基础,也是新基建的重要组成部分...

一只猿的自我修养 4741

MySQL问题记录

MySQL遇到此处错误时(字段多,varchar(255)多的时候) 1118 - Row size too large. The maximum row size for the used table type, not counting BLOBs, is 65535. This includes storage overhead, check the manual. You have to change some columns to TEXT or BLOBs 解决方法:在末尾加上 EN...

yanzanjie2018的博客 1767

FFmpeg流媒体开发避坑指南:avformat_open_input超时设置的那些坑

本文深入剖析了FFmpeg流媒体开发中avformat_open_input函数的超时设置难题。针对默认阻塞行为、无效的timeout参数以及不稳定的线程取消方案等常见误区,文章详细解读了官方推荐的interrupt_callback机制,并提供了健壮的超时控制器实现方案与最佳实践,帮助开发者构建稳定可靠的流媒体应用。

weixin_29239279的博客 237

rk3568 rk628桥片 rgb2hdmi

RK628 是瑞芯微全新推出的视频桥接芯片,支持丰富的显示接口,支持高分辨率大屏产品转换需求。基于DRM、FB的显示框架易于使用。 输入信号支持:HDMI、RGB、BT.1120,输出信号支持 HDMI、GVI、Dual LVDS、Dual MIPI、MIPI-CSI、RGB、BT.1120,最高支持4K 60fps 输入/输出转换,并且支持输入到输出 1/4~4倍的缩放。

weixin_35723192的博客 450

requires XXX>=YYY, but you‘ll have XXXX=ZZZ which is incompatible

这个报错是XXX包版本过低,升级即可 pip install -U XXX

GodGump的博客 18万+

海德汉机床采集数据

海德汉数控系统我一般在高端机床上见得比较多。有好多五轴加工精度比较高的机床都用的是海德汉的系统。市面上常见的有530和640等型号。海德汉的采集还是有点难度的,需要对SDK有深度的了解。

若云流风的专栏 1526

Elasticsearch+logstash+kibana

ELK是包含但不限于Elasticsearch(简称es)、Logstash、Kibana 三个开源软件的组成的一个整体。这三个软件合成ELK。是用于数据抽取(Logstash)、搜索分析(Elasticsearch)、数据展现(Kibana)的一整套解决方案,所以也称作ELK stack。本课程从分别对三个组件经行详细介绍,尤其是Elasticsearch,因为它是elk的核心。本课程从es底层对文档、索引、搜索、聚合、集群经行介绍,从搜索和聚合分析实例来展现es的魅力。Logstash从内部如何采集数据

weixin_56644618的博客 1万+

代谢组数据分析(二十一):通过MetaboAnalystR标准化构建sPLSDA预测模型

本文介绍了如何使用R语言中的MetaboAnalystR包和mixOmics包进行代谢组学数据的标准化和sPLSDA分析。MetaboAnalystR包用于数据预处理,包括数据初始化、清洗、补足、过滤和标准化等步骤,以确保数据质量。mixOmics包则用于sPLSDA分析,通过Lasso惩罚进行变量选择,并建立分类模型。文章详细说明了安装和加载相关R包的步骤,并提供了数据导入和预处理的代码示例。最后,强调了数据预处理的重要性,以确保后续分析的准确性和可靠性。

专注生信领域 2426

【部署】OpenClaw版本降级实操(含全量卸载)

本文详细介绍了OpenClaw工具的降级与卸载方法。主要内容包括:1)通过npm安装指定版本的核心命令及国内镜像加速方案;2)两种卸载路径:CLI工具存在时的简易一键卸载(含交互式与非交互式命令)和手动分步卸载流程;3)CLI已删除但服务仍在运行时,针对macOS(launchd)、Linux(systemd)和Windows(计划任务)系统的具体清理步骤。文章特别强调了卸载前备份的重要性,并提供了不同安装方式(常规安装与源码克隆)的额外说明,确保用户能彻底清理所有组件。

海兰 3171

mongodb源码分析(三)

mongodb源码分析(七)查询3之mongod的cursor的产生(续)     上一篇文章我们说道了mongod对于QueryPlan的选取,由于篇幅过长,所以另起一篇文章接上一篇文章 继续谈plan的实际查询流程.         上一篇文章说完了QueryPlanSet::make我们回到:MultiPlanScanner::init. [cpp

happylife1527的专栏 1174

GEE高阶应用——如何绘制2000-2022年土地利用变化轨迹时序图

土地利用变化是指在一定时间范围内,土地利用类型和结构发生的变化。时序变化是指这种变化随时间的推移而发生的序列变化。土地利用变化轨迹的时序变化具体介绍如下:首先,土地利用变化轨迹的时序变化体现在土地利用类型的演变上。在过去的几十年里,随着人口的增加、经济的发展和城市化的推进,土地利用类型发生了显著的变化。传统的农田逐渐减少,而城市、工业、交通、居住等用地的面积不断扩大。同时,随着环境保护意识的提高,生态保护用地、森林、湿地等绿色用地的面积也在增加。

此星光明博客 1113

leetcode之Best Time to Buy and Sell Stock III 问题

问题描述: Say you have an array for which the ith element is the price of a given stock on dayi. Design an algorithm to find the maximum profit. You may complete at mosttwo transactions.(发现这些问题变化了啥没?)

漫漫学习路 326

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

Devexpress16.2.6破解工具

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

leetcode best-time-to-buy-and-sell-stock-iii(Java)

leetcode题目 best-time-to-buy-and-sell-stock-iii – newcoder 28 买卖股票的最佳时机III – leetcode 123 题目描述 * Say you have an array for which the i th element * is the price of a given stock on day i. * * Des...

聚沙成塔 684

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

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

LeetCode解题 123:Best Time to Buy and Sell Stock III (动态规划)Problem 123: Best Time to Buy and Sell Stock III [Hard]解题思路I. O(2n)时间+O(3n)空间II. O(2n)时间+O(n)空间III. O(n)时间+O(4)空间Solution (Java) Problem 123: B...

Fayedily的博客 491

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

Best Time to Buy and Sell Stock III -- LeetCode

原题链接: http://oj.leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/  这道题是Best Time to Buy and Sell Stock的扩展,现在我们最多可以进行两次交易。我们仍然使用动态规划来完成,事实上可以解决非常通用的情况,也就是最多进行k次交易的情况。 这里我们先解释最多可以进行k次交易的算法,

Code Ganker 4万+

LeetCode Best Time to Buy and Sell Stock III

给定每天的股票价格,如果最多允许两次交易,但手中最多只能持有一支股票,在再次买入的时候必须将之前的股票卖出,求能获取的最大利润。

DRFish 2552

LeetCode123—Best Time to Buy and Sell Stock III

LeetCode123—Best Time to Buy and Sell Stock III

上善若水 1320

LeetCode 123. Best Time to Buy and Sell Stock III(动态规划)

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

da_kao_la的博客 342

Leetcode 123. Best Time to Buy and Sell Stock III 股票买卖3 解题报告

1 解题思想嗯,是的,已经第三题了,数组代表什么我不想再复述一次,自己看: Leetcode 122. Best Time to Buy and Sell Stock II 股票买卖2 解题报告 Leetcode 121. Best Time to Buy and Sell Stock 股票买卖 解题报告这道题的难点或者说同点在于: 只允许买卖两次这道题本质上用的是第一题的方法,我也看了下Di

MebiuW的专栏 3456

LeetCode 123: Best Time to Buy and Sell Stock III

Best Time to Buy and Sell Stock IIISay 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 two tr

一只码畜 421

leetcode 123. Best Time to Buy and Sell Stock III 股票最多两次买入、两次卖出的最大利润

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ 数组的最大2子段和,允许在一天内买入又卖出,相当于不交易。因为题目规定的是最多交易两次,而不是必须交易两次。 class Solution { public: int maxProfit(vector<int>& prices)...

rock4you 314

LeetCode-Best Time to Buy and Sell Stock III算法对比

LeetCode 123.Best Time to Buy and Sell Stock III 由于先做了这类题目的 I II,看到III就直接按照先求局部最大值,取最大的前两个的和。(错误的代码就不贴了。。。)后来一直wrong answer. 忽然明白了限定两手交易,仍然可能将两个局部最大值连起来组成更大数值。一时想不起来解法 看到两个算法: 1.大牛1用分治策略,移动分割点分

catsanddogsman的专栏 561

LeetCode力扣之123. Best Time to Buy and Sell Stock III

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 two transactions.Note:You may not engage...

LeeWei 304

LeetCode123:Best Time to Buy and Sell Stock III

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 two transactions. Note: You ma

3386
上一篇: LeetCode--Best Time to Buy and Sell Stock II
下一篇: 算法概论第八章课后题--8.3
Coder_zyq
博客等级 码龄10年 3粉丝 23原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值