代码如下:
#include <iostream>
using namespace std;
int i, j, n;
int A[1000], first[1000], second[1000];
int max(int a, int b)
{
return a > b ? a : b;
}
int findMin(int A[], int left, int right)
{
int s = 0x7ffffff;
for(i = left; i < right; i++)
{
if(A[i] < s)
s = A[i];
}
return s;
}
int findMax(int A[], int left, int right)
{
int s = -80000000;
for(i = left; i < right; i++)
{
if(A[i] > s)
s = A[i];
}
return s;
}
int maxProfit(int A[], int n)
{
//如果有两次交易
first[0] = 0;
for(i = 1; i < n; i++)
{
first[i] = max(first[i - 1], A[i] - findMin(A, 0, i + 1));
}
second[n - 1] = 0;
for(j = n - 2; j > 0; j--)
{
second[j] = max(second[j + 1], findMax(A, j, n) - A[j]);
}
//求 first[i] + second[i] 的最大值
int s = -80000000;
for(i = 0; i < n; i++)
{
if(first[i] + second[i] > s)
s = first[i] + second[i];
}
//还要考虑只交易一次的情况
int once = first[n - 1];
return once > s ? once : s;
}
int main()
{
cin >> n;
for(i = 0; i < n; i++)
cin >> A[i];
int result;
result = maxProfit(A, n);
cout << result << endl;
}