【问题描述】
小明想要去买股票,但是他不知道什么时候买入什么时候卖出能够获得最大利润,希望你能帮助他。要求给出一支股票在n天内每天的价格,请你计算所能获得的最大利润。需要注意的最多可以完成两笔交易,并且在再次购买之前需要卖出之前的股票。
【输入形式】
第一行输入一个整数n
第二行输入n个整数
【输出形式】
输出一个整数
【样例输入】
8
3 3 5 0 0 3 1 4
【样例输出】
6
【样例说明】
第4天买入,第6天卖出,利润3;第7天买入,第8天卖出,利润3;最大利润6
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
int n;
cin>>n;
int a[100]= {0},profit1[500]= {0},profit2[500]= {0};
for (int i=1; i<=n; i++) {
cin>>a[i];
}
int i,j,k,l;
int sum=0,flag=0;//暂时储存截止到此时刻最大的profit
int count=0;//数组profit[]初始位置
for (i=1; i<=n-3; i++) {
for (j=i+1; j<=n-2; j++) {
for (k=j+1; k<=n-1; k++) {
for (l=k+1; l<=n; l++) {
sum=a[j]-a[i]+a[l]-a[k];
if (sum>flag) {
flag=sum;
profit1[count]=sum;
count++;
}
}
}
}
}
flag=0,count=0;
for (i=1; i<=n-1; i++) {
for (j=i+1; j<=n; j++) {
sum=a[j]-a[i];
if (sum>flag) {
flag=sum;
profit2[count]=sum;
count++;
}
}
}
int max1,max2;
max1=*max_element(profit1,profit1+500);
max2=*max_element(profit2,profit2+500);
int max;
max=max1>max2?max1:max2;
if (max<0) cout<<0;
else cout<<max;
}