1. Title
Given an array of length N, the i-th number in the array represents the price of a given stock on the i-th day.
Design an algorithm to calculate the maximum profit. You can complete as many transactions as possible (buying and selling a stock multiple times) under the following constraints:
You cannot participate in multiple transactions at the same time (you must sell the previous stock before buying again).
After you sell the stock, you cannot buy the stock the next day (ie, the freezing period is 1 day).
Input format The
first line contains the integer N, which represents the length of the array.
The second line contains N positive integers not exceeding 10000, which represents a complete array.
Output format
Output an integer, which represents the maximum profit.
Data range
1≤N≤105
Input example:
5
1 2 3 0 2
Output example:
3
Sample explanation The
corresponding transaction status is: [Buy, Sell, Freezing Period, Buy, Sell], the first transaction can get profit 2- 1 = 1, the second transaction can get a profit of 2-0 = 2, and the total profit will be 1+2 = 3.
2. Thinking
Status analysis:
State representation:
Status meaning:
f[i][0
]: It means considering the i day, there are stocks in hand and have not been sold yet.
f[i][1]
: Means to consider the i day, the first day when there is no stock in hand.
f[i][2]
: I said it was considering the first day, did not have a stock of> = 2-day
state transition equation:
f[i][0]=max(f[i-1][0],f[i-1][2]-w[i])
;
the first i
day of the hands as well as the stock can be from i-1
no stock and after a day in the hands of freezing period and i-1
day of the hands as well as stock transfer over.
f[i][1]=f[i-1][0]+w[i]
; There is no stock in the hand on the
first i
day, only the stock in the i-1
hand on the first day and then the stock is sold and transferred.
f[i][2]=max(f[i-1][1],f[i-1][2])
;
The i
number of >=2
days when there is no stock in the hand can be transferred from the 1
day when there is no stock in the hand and the number of days when there is no stock in the hand >1
.
Code
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int N=1e5+10,INF=0x3f3f3f3f;
int f[N][3];
int w[N];
int main()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%d",&w[i]);
f[0][1]=f[0][0]=-INF; //初始化,将入口设置为合法状态,其他状态设置为非法
f[0][2]=0;
for(int i=1;i<=n;i++)
{
f[i][0]=max(f[i-1][0],f[i-1][2]-w[i]);
f[i][1]=f[i-1][0]+w[i];
f[i][2]=max(f[i-1][1],f[i-1][2]);
}
printf("%d\n",max(f[n][2],f[n][1]));
return 0;
}