Best Time to Buy and Sell Stock

leetcode难题之Best time to buy and sell stock大合集 这次带来的是Best time to buy and sell stock大合集,在leetcode上这一合集共有6道题,难度从easy到hard不等,我们这次记录下这一合集的全部解法并记录下解题的思考想法。所有的题目都是计算不同计算规则下股票的最大利润。 一,Best Time to Buy and Sell Stock (一次交易) Say you have an array for w... 阅读详情

Best Time to Buy and Sell Stock 

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 complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

solution:
dp[i] contains the smallest prices until i-day;
the state transition equation is:
if prices[i] < dp[i - 1] then dp[i] = prices[i];
if prices[i] >= dp[i - 1] then dp[i] = dp[i-1];

int maxProfit(vector<int>& prices) 
{
    int n = prices.size();
    if (n <= 0) return 0;
    int max_profit = 0;
    int *dp = new int[n]();
    //memset(dp,0,sizeof(int)*n);
    for (int i = 0; i < n; ++i)
    {
        if (i == 0 || prices[i] < dp[i - 1])
            dp[i] = prices[i];
        else
        {
            dp[i] = dp[i - 1];
            max_profit = max(max_profit, prices[i] - dp[i]);
        }
    }
    delete[]dp;
    return max_profit;
}

duo to the fact that dp[i] only relies on previous state, we have the simplied form:
int maxProfit(vector<int>& prices) 
{
    int n = prices.size();
    if (n <= 0) return 0;
    int max_profit = 0, smallest_price = 0;
    for (int i = 0; i < n; ++i)
    {
        if (i == 0 || prices[i] < smallest_price)
            smallest_price = prices[i];
        else
            max_profit = max(max_profit, prices[i] - smallest_price);
    }
    return max_profit;
}
 
Best Time to Buy and Sell Stock
 2 

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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

solution:

reference: https://leetcode.com/discuss/71354/share-my-thinking-process

2 possible transactions: buy and sell 

buy[i] means before day i what is the maxProfit for any sequence end with buy.

sell[i] means before day i what is the maxProfit for any sequence end with sell.

state transition equation is: 

buy[i] = max(sell[i-1]-price, buy[i-1]) 

sell[i] = max(buy[i-1]+price, sell[i-1])

int maxProfit(vector<int> &prices) 
{
    int buy(INT_MIN), sell(0), prev_sell(0), prev_buy;
    for (int price : prices) 
    {
        prev_buy = buy;
        prev_sell = sell;
        buy = max(prev_sell - price, buy);
        sell = max(prev_buy + price, sell);
    }
    return sell;
}
 another solution: greedy algorithm
int maxProfit(vector<int>& prices) 
{
    int max_profit= 0;
    for(int i=1;i<prices.size();++i)
    {
        max_profit += max(0,prices[i]-prices[i-1]);
    }
    return max_profit;
}
 

Best Time to Buy and Sell Stock 3 

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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:   You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).   After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day) 

solution:

reference: https://leetcode.com/discuss/71354/share-my-thinking-process 

state transition equation is: 

buy[i] = max(sell[i-2]-price, buy[i-1]) 

sell[i] = max(buy[i-1]+price, sell[i-1])

int maxProfit(vector<int> &prices) 
{
    int buy(INT_MIN), sell(0), prev_sell(0), prev_buy;
    for (int price : prices) 
    {
        prev_buy = buy;
        buy = max(prev_sell - price, buy);
        prev_sell = sell;
        sell = max(prev_buy + price, sell);
    }
    return sell;
}
 

Best Time to Buy and Sell Stock 4 

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.

solution:

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 

int maxProfit(vector<int> &prices,int K) 
{
    if (prices.size() <= 1) return 0;
    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;
}


Warning-[INFL_DELTA] Too many events zero delay loop 项目场景: 运用VCS工具执行仿真的时候,遇到如下错误提示,但仿真还在继续。 Warning-[INFL_DELTA] Too many events Possible zero delay loop. Too many events in the simulation at time 0 fs. 问题描述: 为什么会有这个问题; 什么导致了这个问题; 原因分析: 1、为什么会有这个问题 由于竞争条件或编码风格不明确,可能会产生零延时回路,导致仿真挂起或仿真时间无限。 2、什么导致了这个问题 举 阅读详情

相关推荐

新手必看:如何用PhaGCN2和vConTACT2搞定宏病毒组注释(附避坑指南)

本文为宏病毒组研究新手提供了使用PhaGCN2和vConTACT2进行病毒注释的完整实战指南。内容涵盖从Conda环境配置、软件安装、参数解析到结果解读的全流程,并重点分享了整合双工具进行交叉验证的策略与常见报错解决方案,旨在帮助研究者高效、准确地完成病毒分类注释工作。

j2k3l4的博客 808

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

聚沙成塔 686

STM32串口接收避坑指南:为什么你的USART_IT_IDLE中断不触发?附完整调试流程

本文深入解析STM32串口接收中断机制,特别是USART_IT_IDLE中断不触发的常见原因及解决方案。通过详细分析中断标志清除顺序、波特率配置、硬件连接等关键因素,并提供完整的调试流程和代码示例,帮助开发者快速定位并解决串口通信问题。

weixin_42519985的博客 354

Leetcode Best Time to Buy and Sell Stock python 问题解析

Leetcode 121题 Best Time to Buy and Sell Stock 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 complete at most one transaction (i....

润泽的博客 286

RRAM/ Near Memory Computing (NMC) Survey - Reading Notes 0707

Reading Notes of Resistive Random Access Memory – Day 2 Chapter 3 RRAM Characterization and Modeling Overview of RRAM Physical Mechanism A general picture for the filamentary switching mechanism. Forming: 对本征RRAM样本,加电压VformingV_{forming}Vforming​,中间氧化层的O

Blog of Lucky H6 997

2025.06.20【pacbio】|PB甲基化分析结果的统计与可视化介绍

本文介绍了PacBio甲基化数据的统计分析与可视化方法。主要内容包括:1) 分析甲基化位点分布、比例及染色体分布;2) 修饰基序(Motif)的统计与热图展示;3) 全基因组和局部区域测序深度可视化;4) 使用IGV查看单个reads修饰情况。文章提供了R代码示例,涵盖柱状图、分布图、热图等多种可视化形式,并建议了差异甲基化分析等进阶方法,帮助科研人员深入挖掘甲基化数据。

2074

Best Time to Buy and Sell Stock 系列总结

Best Time to Buy and Sell Stock 系列总结 强烈推荐: Most consistent ways of dealing with the series of stock problems, 耐心仔细的全部看完, 收获不小. Best Time to Buy and Sell Stock 系列有如下题目, 均可用动态规划进行求解, 有通用的递推公式: 121. Bes...

珍妮的选择的博客 261

SRAM compiler中 Number of banks 设置

的值时,需要考虑应用的性能需求、功耗要求和面积限制。设计者应根据具体的应用场景选择合适的bank数量,以优化整体系统性能。bank是一种用于分离存储器访问的设计结构,允许同时对不同的存储区域进行读写操作,从而提高存储器的并发访问性能。选项用于指定 SRAM 存储器的 并发存储区域。在 SRAM 编译器中,

hzmscut的博客 1884

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.(发现这些问题变化了啥没?)

漫漫学习路 329

【机器学习】随机森林(Random Forest,简称 RF):预测光伏电站功率 || 缺失数据处理 || 重复行处理...

【机器学习】随机森林(Random Forest,简称 RF):预测光伏电站功率。

追光者♂:记录、分享、总结、提升,现象级专栏《Python从入门到人工智能》作者,无惧黑暗,坚信曙光 1660

uniapp - 强力解决H5网页浏览器跨域问题,如何解决uniapp请求接口在浏览器跨域问题,UniApp H5 跨域代理配置详细教程完美解决所有uniapp跨域(调用第三方接口或服务器api跨域)

uni-app 跨域,uniApp解决h5跨域问题,解决uni-app请求接口在浏览器跨域问题,uni.request请求跨域问题解决方案,uni-app-跨域解决方法,彻底解决uniapp发布为H5的跨域问题,uniapp H5页面设置跨域请求_uniapp h5跨域配置,uniapp开发 H5 解决跨域问题,uniApp请求解决跨域问题,uniapp request如何实现前端请求跨域,解决uniapp调试过程中的请求跨域和环境配置,Uniapp调用外部api接口跨域请求,uni-app发布H5页面跨域

🏆 前端领域优质创作者 5361

第十周 Best Time to Buy and Sell Stock III

Best Time to Buy and Sell Stock III LeetCode上的123题:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/ 文章目录Best Time to Buy and Sell Stock III题目题解代码 题目 给出一个大小为n的数组,表示从1到n天股票的价格。有两次交易机会(...

tmhf_cc的博客 557

LeRobot 官方论文:一个用于端到端机器人学习的开源库

本文介绍了一个名为LeRobot的开源库,旨在解决机器人学习领域的碎片化问题。该库提供了端到端的技术栈,包括统一的机器人中间件API、标准化的数据集格式(LeRobotDataset)、优化的推理栈以及多种最先进机器人学习算法的实现。LeRobot支持多种低成本开源机器人平台(如SO-10X、ALOHA-2等),通过共享中间件实现便捷的遥操作和数据收集。其数据集格式已广泛应用于社区,截至2025年9月已有16,000多个数据集公开共享。该库还支持流式处理大规模数据,降低了研究门槛。在模型方面,LeRobot

2506_90492529的博客 918

【LeetCode】解题122:Best Time to Buy and Sell Stock II

LeetCode解题 122:Best Time to Buy and Sell Stock II Problem 122: Best Time to Buy and Sell Stock II [Easy]解题思路Solution (Java) Problem 122: Best Time to Buy and Sell Stock II [Easy] Say you have an array...

Fayedily的博客 369

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

LeetCode Array 121 122 Best Time to Buy and Sell Stock I II

Array 121. Best Time to Buy and Sell Stock 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 complete at most one transaction (i.e.,...

Yi Jiao's Blog 159

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

309. Best Time to Buy and Sell Stock with Cooldown

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/ 1. 思路 https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/75928/Share-my-DP-solution-(B...

scut_salmon的博客 249

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

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

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

聚沙成塔 484

122. Best Time to Buy and Sell Stock II

文章目录122. Best Time to Buy and Sell Stock IIDescriptionSolutionsSubmissionsSummary 122. Best Time to Buy and Sell Stock II https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/ Description ...

La La Land 144

leetcode 122 Best Time to Buy and Sell Stock II 详细解答

leetcode 122 Best Time to Buy and Sell Stock II 详细解答 解答1 假设有一个图像代表数组: > https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/solution/ 最后需要求得的答案就是,每一段的递增区间的差值。所以得到代码如下: 解法2 上面解法比较hack, 不推荐。 就股票买卖来说,买入股票自身的价格就会 -Price,卖出股票自身的价格就是 +Price. 利

qq_22210659的博客 270

【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

leetcode 121. Best Time to Buy and Sell Stock

leetcode-121 Best Time to Buy and Sell Stock (Easy) 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 complete at most one transacti...

Night_Thief的博客 167

121. Best Time to Buy and Sell Stock

题目来源: 121.Best Time to Buy and Sell Stock 自我感觉难度/真实难度: 题意: 分析: 自己的代码: class Solution: def maxProfit(self, prices: List[int]) -> int: length=len(prices) det...

weixin_30596735的博客 75

【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

[刷题]leetcode #309 - Best Time to Buy and Sell Stock with Cooldown

题目 代码 class Solution { public int maxProfit(int[] prices) { if (prices.length <= 1) return 0; int l = prices.length; int a=0, b = -prices[0], c = 0; for (int i = 1; i < l; ++i){ int temp = a;

qq_27637285的博客 311

Best Time to Buy and Sell Stock - LeetCode

目录 题目链接 注意点 解法 小结 题目链接 Best Time to Buy and Sell Stock - LeetCode 注意点 在卖出之前必须要先购入 解法 解法一:遍历一遍,随时记录当前数字之前的最小的数字。将当前数字与当前最小数字相减查看收益。时间...

weixin_30335353的博客 92

Leetcode 121. Best Time to Buy and Sell Stock

Leetcode 121. Best Time to Buy and Sell Stock 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 complete at most one transaction (i.e...

fengran_mark的博客 140
下一篇: Linux内核栈与用户栈分析
wusanyee
博客等级 码龄12年 1粉丝 4原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值