知识点:动态规划
思路:求最长子序列,要满足左边升序,右边降序。核心是能列出状态转移方程。
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv){
int dp1[100], dp2[100], num[100];
int ans = 0;
int n;
int i, j;
//inputs
scanf("%d", &n);
for(i = 0; i < n; i++){
scanf("%d", &num[i]);
}
//calculate increasing sub-sequence and save the outcomes in array dp1[]
for(i = 0; i < n; i++){
dp1[i] = 1;
for(j = 0; j < i; j++){
if(num[j] < num[i] && dp1[i] < dp1[j] + 1){//the contition&state trasfer equation
dp1[i] = dp1[j] + 1;
}
}
}
//calculate decreasing sub-sequence
for(i = n - 1; i >= 0; i--){
dp2[i] = 1;
for(j = n - 1; j > i; j--){
if(num[j] < num[i] && dp2[i] < dp2[j] + 1){
dp2[i] = dp2[j] + 1;
}
}
}
//get the result
for(i = 0; i < n; i++){
if(ans < dp1[i] + dp2[i] - 1){
ans = dp1[i] + dp2[i] - 1;
}
}
printf("%d\n", n - ans);
system("pause");
return 0;
}