public int maxProfit(int[] prices) {
int n = prices.length;
if (n==0) return 0;
// 最多两次买卖 两次 买卖 一共有五个阶段
int[][] f = new int[n+1][6];
// 1 持币观望 2 买入 3卖出 持币观望 4 第二次买入 5 第二次卖出 持币观望
f[0][1] = 0;
//前0天 一阶段 最大获利 为 0
f[0][2] = Integer.MIN_VALUE;
f[0][3] = Integer.MIN_VALUE;
f[0][4] = Integer.MIN_VALUE;
f[0][5] = Integer.MIN_VALUE;
// 1 3 5
for (int i = 1; i <=n ; i++) {
for (int j = 1; j <=5 ; j+=2) {
f[i][j] =f[i-1][j];
if (j>1&&i>1&&f[i-1][j-1]!=Integer.MIN_VALUE){
f[i][j] = Math.max(f[i][j],f[i-1][j-1]+prices[i-1]-prices[i-2]);
}
}
for (int j = 2; j <=5 ; j+=2) {
f[i][j] = f[i-1][j-1];
if (i>1&&f[i-1][j]!=Integer.MIN_VALUE){
f[i][j] = Math.max(f[i][j],f[i-1][j]+prices[i-1]-prices[i-2]);
}
if (j>2&&i>1&&f[i-1][j-2]!=Integer.MIN_VALUE){
f[i][j] = Math.max(f[i][j],f[i-1][j-2]+prices[i-1]-prices[i-2]);
}
}
}
return Math.max(f[n][1],Math.max(f[n][3],f[n][5]));
}
public int maxProfit(int k, int[] prices) {
// write your code here
int n = prices.length;
if (n==0 ) return 0;
if (k>n) {
int res =0;
for (int i = 0; i <n-1 ; i++) {
res+= Math.max(0,prices[i+1]-prices[i]);
}
return res;
}
int f[][] = new int[n+1][2*k+2]; //描述右2k+1个阶段
f[0][1] =0;
for (int i = 2; i <2*k+2 ; i++) {
f[0][i] = Integer.MIN_VALUE;
}
for (int i = 1; i <=n ; i++) {
for (int j = 1; j <=2*k+1 ; j+=2) {
f[i][j] =f[i-1][j];
if (j>1&&i>1&&f[i-1][j-1]!=Integer.MIN_VALUE){
f[i][j] = Math.max(f[i][j],f[i-1][j-1]+prices[i-1]-prices[i-2]);
}
}
for (int j = 2; j <=2*k+1 ; j+=2) {
f[i][j] = f[i-1][j-1];
if (i>1&&f[i-1][j]!=Integer.MIN_VALUE){
f[i][j] = Math.max(f[i][j],f[i-1][j]+prices[i-1]-prices[i-2]);
}
if (i>1&&j>2&&f[i-1][j-2]!=Integer.MIN_VALUE){
f[i][j] = Math.max(f[i][j],f[i-1][j-2]+prices[i-1]-prices[i-2]);
}
}
}
int max =0;
for (int i = 0; i <=2*k+1 ; i++) {
max =Math.max(max,f[n][i]);
}
return max;
}
public int longestIncreasingSubsequence(int[] nums) {
// write your code here
int n = nums.length;
if (n==0) return 0;
int[] f = new int[n];
// f[i] 表示 以 nums[i] 结尾的最长上升子序列的长度
int res =0;
for (int i = 0; i <n ; i++) {
f[i] =1;
for (int j = 0 ; j <i ; j++) {
if (nums[i]>nums[j]&