股票专家小明

【问题描述】

小明想要去买股票,但是他不知道什么时候买入什么时候卖出能够获得最大利润,希望你能帮助他。要求给出一支股票在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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值