[Explanations] stock trading

Title Description

  Recently more and more people will join the stock market, Fu also a little heart. Remember the "stock market risk, investors must be careful," Fu decided to look at a simplified version of the stock trading issue.

  Fu has been assumed that accurately predicted the price of a stock in the next N days, he hopes the sale of the two, making the highest profits obtained. To calculate the simplicity, the profit is calculated as the selling price minus the purchase price.

  On the same day can be traded several times. But after the first purchase, you must first sell before they can buy a second time.

  Now, Fu wanted to know how much profit he can get up to.

 

Input Format

  The first line of the input is an integer T (T≤50), T represents a total set of data.

  Next, each group of data, the first line is an integer N (1≤N≤100,000), N represents a total day. The second line is the N separated by spaces integer that indicates the stock price every day. The absolute value of the daily stock price will not exceed 1,000,000.

 

Output Format

  For each data output line. The line contains an integer representing the maximum profit that can be obtained Fu.

 

SAMPLE INPUT

3

7

5 14 -2 4 9 3 1

7

6 6 8 7 4 1 -2

4

18 9 5 2

 

Sample Output

28

2

0

 

answer

  We can use $ dp1 [i] $ denotes $ 1 $ day to the first $ i $ the first day of trading the maximum stock, $ dp2 [i] $ denotes the $ i $ the first day of the second trading day $ n $ times the maximum stock.

  易得$ans = \underset{1 \leqslant i \leqslant n}{max} \left \{ dp1[i] + dp2[i] \right \}$。

#include <iostream>
#include <cstdio>

#define MAX_N (100000 + 5)

using namespace std;

int T;
int n;
int a[MAX_N];
int dp1[MAX_N], dp2[MAX_N];
int ans;

int main()
{
    scanf("%d", &T);
    int mina, maxa;
    while(T--)
    {
        scanf("%d", &n);
        for(register int i = 1; i <= n; ++i)
        {
            scanf("%d", a + i);
        }
        dp1[0] = dp2[n + 1] = ans = -0x7f7f7f7f;
        mina = 0x7f7f7f7f;
        maxa = -0x7f7f7f7f;
        for(register int i = 1; i <= n; ++i)
        {
            mina = min(mina, a[i]);
            dp1[i] = max(dp1[i - 1], a[i] - mina);
        }
        for(register int i = n; i; --i)
        {
            maxa = max(maxa, a[i]);
            dp2[i] = max(dp2[i + 1], maxa - a[i]);
        }
        for(register int i = 1; i <= n; ++i)
        {
            ans = max(ans, dp1[i] + dp2[i]);
        }
        cout << ans << "\n";
    }
    return 0;    
}
Reference program

 

Guess you like

Origin www.cnblogs.com/kcn999/p/10959829.html