# Dynamic Planning--State Machine--Stock Trading IV

Given an array of length N, the number i in the array represents the price of a given stock on day i. Design an algorithm to calculate the maximum profit you can make, and you can complete up to k transactions.
Note: You cannot participate in multiple transactions at the same time (you must sell your previous shares before you buy them again). One purchase and one sale make one transaction.
Input Format Design

The first line contains the integers N and k, indicating the length of the array and the maximum number of transactions you can complete.
The second line contains N positive integers not exceeding 1000, representing the complete array.
Output Format
Output an integer representing the maximum profit.
Data Range
1≤N≤10^5,
1≤k≤100

Input Sample 1:

3 2
2 4 1
Output Sample 1:

2
Input Sample 2:

6 2
3 2 6 5 0 3
Output Sample 2:

7
Sample Interpretation
Example 1: Buy on day 1 (stock price = 2) and sell on day 2 (stock price = 4), and the exchange will make a profit = 4-2 = 2.

Example 2: Buy on the second day (stock price = 2) and sell on the third day (stock price = 6), and the exchange will make a profit = 6-2 = 4. Subsequently, buy on the fifth day (stock price = 0) and sell on the sixth day (stock price = 3), and the exchange will make a profit = 3-0 = 3. The total profit is 4+3 = 7.
Analysis:
This topic requires that transactions not exceed the maximum profit earned by k transactions, one transaction being a transaction. ```#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N =  100005,M = 105;
int f[N][M];
int main(){
int n,k,price;
scanf("%d%d",&n,&k);
memset(f,-0x3f,sizeof f);
f = 0;
for(int i = 1;i <= n;i++){
scanf("%d",&price);
f[i] = 0;
for(int j = 1;j <= k;j++){
f[i][j] = max(f[i-1][j],f[i-1][j]+price);
f[i][j] = max(f[i-1][j-1]-price,f[i-1][j]);
}
}
int res = 0;
for(int i = 0;i <= k;i++)   res = max(res,f[n][i]);
printf("%d\n",res);
return 0;
}
```

Since the state on day I only uses the state on day i-1, it can be implemented with a rolling array, requiring an inverted enumeration of transactions to prevent the required state from being overwritten.

```#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int M = 105;
int f[M];
int main(){
int n,k,price;
scanf("%d%d",&n,&k);
memset(f,-0x3f,sizeof f);
f = 0;
for(int i = 1;i <= n;i++){
scanf("%d",&price);
for(int j = k;j >= 1;j--){
f[j] = max(f[j],f[j]+price);
f[j] = max(f[j-1]-price,f[j]);
}
}
int res = 0;
for(int i = 0;i <= k;i++)   res = max(res,f[i]);
printf("%d\n",res);
return 0;
}
For reference only.
```

Tags: C Dynamic Programming

Posted on Sun, 03 Oct 2021 12:48:54 -0400 by blkraven