当前位置:网站首页>第三讲:股票买卖 III
第三讲:股票买卖 III
2022-07-13 18:42:00 【奋斗吧!骚年!】
题目:AcWing 1056. 股票买卖 III
给定一个长度为 N 的数组,数组中的第 i 个数字表示一个给定股票在第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你最多可以完成两笔交易。
注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
输入格式
第一行包含整数 N,表示数组长度。
第二行包含 N 个不大于 109 的正整数,表示完整的数组。
输出格式
输出一个整数,表示最大利润。
数据范围
1≤N≤105
输入样例1:
8
3 3 5 0 0 3 1 4
输出样例1:
6
输入样例2:
5
1 2 3 4 5
输出样例2:
4
输入样例3:
5
7 6 4 3 1
输出样例3:
0
样例解释
样例1:在第 4 天(股票价格 = 0)的时候买入,在第 6 天(股票价格 = 3)的时候卖出,这笔交易所能获得利润 = 3-0 = 3 。随后,在第 7 天(股票价格 = 1)的时候买入,在第 8 天 (股票价格 = 4)的时候卖出,这笔交易所能获得利润 = 4-1 = 3 。共得利润 3+3 = 6。
样例2:在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4 。注意你不能在第 1 天和第 2 天接连购买股票,之后再将它们卖出。因为这样属于同时参与了多笔交易,你必须在再次购买前出售掉之前的股票。
样例3:在这种情况下, 不进行任何交易, 所以最大利润为 0。
题目分析:
如果我们只进行一次交易,那么我们可以通过遍历,用minv维护前面 i 天的最小值,那么第 i 天最大值就会等于g[ i ] = max ( g[ i - 1 ] , p[ i ] - minv )(前面天的最大值,或者当前天)
那么如果可以进行两次交易呢?
我们可以提前将所有天的前i天最大交易值进行打表,然后我们使用相同方法将后i天的最大交易值进行打表,通过枚举分割点找出最大值。
这样时间复杂度就是O(n)
#include <iostream>
using namespace std;
const int N = 100010;
int p[N],g[N],f[N];
int n;
int main()
{
cin>>n;
for(int i=1;i<=n;i++)cin>>p[i];
// 计算在前i天的最大交易
for(int i=1,minv=p[1];i<=n;i++)
{
g[i]=max(g[i-1],p[i]-minv);
minv=min(minv,p[i]);
}
// 计算在i天后的最大交易
for(int i=n-1,maxv=p[n];i>=1;i--)
{
f[i]=max(f[i+1],maxv-p[i]);
maxv=max(maxv,p[i]);
}
int res=0;
// 枚举分割点
for(int i=2;i<=n;i++)res=max(res,g[i]+f[i+1]);
cout<<res<<endl;
return 0;
}
边栏推荐
猜你喜欢

I used Kaitian platform to build an urban epidemic prevention policy inquiry system. Don't you try it?

Wechat classroom appointment of applet completion works (5) assignment

win11触控板用不了怎么办?win11触控板用不了的解决方法

Wechat payment apiv3 unified callback interface encapsulation (H5, jsapi, H5, app, applet)

win10系统如何实现开机启动程序?用shell:startup命令

测试基础4

Test basis 2

左倾堆 - 解析与实现

CVPR | self enhanced unpaired image defogging based on density and depth decomposition
![[I2C (Analog) drive ssd1306 OLED screen of Renesas ra6m4 development board]](/img/51/ac8e0d9e3638f080f134dceb50d4aa.png)
[I2C (Analog) drive ssd1306 OLED screen of Renesas ra6m4 development board]
随机推荐
Test basis 4
An XML file example
一个简单的表单例子
【Renesas RA6M4开发板之按键和LED的GPIO】
No one really thinks that chatting robots are difficult -- using Bert to load the pre training model to get Chinese sentence vectors
杰理之IR 可能出现丢码问题【篇】
The mental journey of a sealer maintainer
[unity] preliminary discussion
VRRP基础配置
想成为硬件工程师,难不?
HJ3 明明的随机数 HJ03
STM32 realizes nRF24L01 communication
How to solve the problem that the computer shared file cannot be opened
2022 cloud native programming challenge starts! Tutor analysis service grid competition questions
Solve the problem that the chip cannot be recognized by opening the official routine after the gd32f20x support package is installed
No one really thinks that chatting robots are difficult -- fine tune the Bert model to get the similarity between sentences
手把手教你安装CUDA
Introduction to word2vec and the application of CNN in natural language
杰理之播 LINEIN 提示音以后可能出现死机【篇】
[Unity] 初探