首页 > 其他分享 >买卖股票的最佳时机 IV - 困难

买卖股票的最佳时机 IV - 困难

时间:2024-12-20 10:29:35浏览次数:6  
标签:firstBuy buy 买卖 int max IV 最佳时机 prices 利润

*************
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 length
 
        int firstBuy = - prices[0];
        int firstSale = 0;
        int secondBuy = - prices[0];
        int secondSale = 0;
 
        // do sth. here
        for (int i = 1; i < n; i++){
            firstBuy = max(firstBuy, - prices[i]);
            firstSale = max(firstSale, prices[i] + firstBuy);
 
            // the second sale
            secondBuy = 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.

标签:firstBuy,buy,买卖,int,max,IV,最佳时机,prices,利润
From: https://blog.csdn.net/ElseWhereR/article/details/144538319

相关文章

  • Hive其三,数据库操作,小技巧设置,加载数据等操作
    目录一、操作数据库二、关于表的操作1)关于字符类型的2)创建表3)修改表4)删除表5)小案例演示三、Hive中经常使用的小技巧的设置四、加载数据1)加载本地数据:2)从HDFS加载到Hive中:3)将数据直接放入表对应的文件夹下4)从其他表中加载数据5)克隆表数据五、通过hive进行......
  • 如何使用position:relative内的absolute元素水平和垂直居中?
    在前端开发中,我们经常需要使元素在其父元素内部水平和垂直居中。当父元素设置为position:relative,而子元素设置为position:absolute时,可以通过以下步骤实现:设置父元素为相对定位(position:relative):这会创建一个新的定位上下文,使得子元素的绝对定位是相对于这个父元素......
  • 跨平台交叉编译 Native AOT
    如何将.NET应用程序发布到鸿蒙上,肯定是很多人感兴趣的话题,目前.NET完全具备可以在OpenHarmony系统上运行的能力,.NET现在有很多选项CoreCLR、Mono和NativeAOT。由于OpenHarmony的沙箱环境的限制,NativeAOT是最佳选择。孙策同学经过几个月的探索,他2024年12月14日在上海举办的.NETC......
  • Ansible:一键部署Keepalived高可用集群
    使用Ansible工具一键部署Keepalived服务1.需求分析使用ansible部署keepalived服务的过程中,需要实现:1.1多系统支持根据不同的系统,自动选择对应的安装方式。可通过相关的环境变量结合 when实现。1.2源码安装考虑到rpm安装的方式会需要依赖一些基础环境,以及版本较低,将采用源......
  • 【01】优雅草央千澈详解关于APP签名以及分发-上架完整流程-如何将安卓APP-apk包和IOS
    【01】优雅草央千澈详解关于APP签名以及分发-上架完整流程-如何将安卓APP-apk包和IOS苹果app-ipa包上架至应用商店-安卓以华为|小米|vivo|oppo|应用宝为例-苹果上架以appstore为例合计三篇背景介绍2024年12月13日优雅草APP分发平台youyacao.cn建立,提供服务(优雅草2019年就曾建......
  • 一文彻底弄懂MySQL的各个存储引擎,InnoDB、MyISAM、Memory、CSV、Archive、Merge、Fede
    MySQL中的存储引擎是其数据库管理系统的核心模块,用于处理不同类型的数据存储和检索操作。每种存储引擎都有自己的特点,适用于不同类型的应用场景。MySQL最常用的存储引擎包括 InnoDB、MyISAM、Memory、CSV、Archive、Merge、Federated、NDB 等。以下是对MySQL存储引擎的详......
  • HivisionIDPhotos - 轻量级的 AI 证件照制作工具
    HivisionIDPhotos是一款简单易用的AI证件照制作工具,能够生成标准证件照和六寸排版照。它提供了简洁的Web界面和API服务,即使在没有GPU的电脑上也能够运行,支持抠图、尺寸调整和自定义底色等功能。8000Stars714Forks14Issues18贡献者Apache-2.0LicensePython......
  • 在Excel中绘制ActiveX控件:解决文本编辑框定位问题
    目录引言问题描述解决方案方法1:使用Range对象的Left和Top属性方法2:使用相对位置方法3:使用单元格作为参考结论代码实现​​​​​​​引言在Excel中添加ActiveX控件,如按钮和文本编辑框,可以极大地增强工作表的交互性。然而,定位这些控件可能会遇到一些挑战。在本文中,......
  • 视频监控管理Liveweb视频监控汇聚平台视频监控系统接入与应用
    随着国内视频监控应用的迅猛发展,系统接入规模不断扩大。不同平台提供商的接入协议差异导致终端制造商在维护时需要针对不同平台的软件版本提供不同的支持,造成资源的巨大浪费。为响应国家对重特大事件的视频监控集中调阅需求,深圳好游科技采用公安部科技信息化局提出的GB/T28181......
  • 视频监控系统/视频汇聚融合平台Liveweb视频云平台解决方案
    GB28181视频监控国标平台Liveweb是基于国标GB28181协议、支持多路设备同时接入的视频监控/视频云服务平台,支持对多平台、多终端分发RTSP、RTMP、FLV、HLS、WebRTC等格式的视频流。国标GB28181平台Liveweb可提供视频直播监控、云端录像、云存储、检索回放、智能告警、语音对讲、......