Meaning of the questions: tell the N-day stock prices, were two transactions, multiple operations can be performed on the same day, but then you must first buy, you must first sell before they can buy a second time. Q. What is the maximum profit?
- dp [i] i days before the first transaction to maximize profits
- dp[i] = max(dp[i-1],num[i]-minn)
- Is not the first day i sell: i-1 equal before the day for the first time get the maximum profit exchange
- I was the first day sold: maximum profit for minimum price minus the n-th day before the stock price of n days
- DP2 is [i] for the i-th day to obtain the maximum value of the sum of the two exchanges the second profit
- dp2[i]=max(dp[i],dp2[i-1]+num[i]-num[i-1])
- Was the second day i buy: it is the sum of two days ago i once the largest trading profit, trading profit for the second time 0
- Is not the first day i bought: i-1 equal to the first day to sell, plus the difference between the stock price and the i-th day of the first i-1 stock price of the day
- If the transaction only once a day, similar to the solution. dp2 [i] is the second consideration is not the first i-1 days to buy.
- dp2[i] =max(dp[i-2]+num[i]-num[i-1],dp2[i-1]+num[i]-num[i-1])
#include <stdio.h> #include <stdlib.h> #include <limits.h> #include <string.h> #include <assert.h> #include <queue> #include <vector> #include<list> #include <algorithm> #include<iostream> #include<math.h> using namespace std; #define N 100005 #define Inf 0x3f3f3f3f int num[N]; int dp[N]; int dp2[N]; int minValue[N]; int main() { int t; cin>>t; while(t--){ int n; scanf("%d",&n);; memset(num,0,sizeof(num)); memset(dp,0,sizeof(dp)); memset(dp2,0,sizeof(dp2)); memset(minValue,0,sizeof(minValue)); int maxx = -1; int minn =Inf; for(int i=1;i<=n;i++){ scanf("%d",&num[i]); if(minn>num[i]){ minn = num[i]; } dp[i] = max(dp[i-1],num[i]-minn); } for(int i=2;i<=n;i++){ dp2[i] = max(dp[i],dp2[i-1]+num[i]-num[i-1]); if(maxx<dp2[i]){ maxx= dp2[i]; } } cout<<maxx<<endl; } return 0; }