
思路:只能持有一个股票所以要么卖出要么买入,最多交易k次,那么我们就用dp[i][j][0/1]表示前i天交易j次当前没有/有股票的最大利润。如果第i天交易j次时手上没有股票那么就有2种可能
1.在前i-1天已经交易了j次没有股票了
2.在前i-1天是持有第j次交易的股票,然后在第i天吧股票的卖掉了
dp[i][j][0]=max(dp[i-1][j][0],dp[i-1][j][1]+a[i])
当第i天持有股票时也是2种状态
1.在前i-1天的时候已经持有了股票
2.在前i-1天的时候不持有股票然后在第i天买入了第j次交易的股票
dp[i][j][1]=max(dp[i-1][j-1][0]-a[i],dp[i-1][j][1])
初始化时先都置为-inf,在前N天的第0次交易且不持有股票时的值都是0.
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <set>
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define SIS std::ios::sync_with_stdio(false)
#define space putchar(' ')
#define enter putchar('\n')
#define lson root<<1
#define rson root<<1|1
typedef pair<int,int> PII;
const int mod=1e9+7;
const int N=2e6+10;
const int M=1e3+