fork download
  1. program mountain;
  2. Uses Math;
  3. const
  4. MAXN = 100005;
  5.  
  6. var
  7. ANS, N, i, j, maxMountainLength, count : LongInt;
  8. P, leftLIS, rightLIS, valli, scartato : Array[0..MAXN-1] of LongInt;
  9.  
  10. begin
  11.  
  12. (*assign(input, 'input.txt'); reset(input);
  13.   assign(output, 'output.txt'); rewrite(output);*)
  14.  
  15. ReadLn(N);
  16.  
  17. for i:=0 to N-1 do
  18. Read(P[i]);
  19. ReadLn();
  20.  
  21. valli[0]:=0; valli[N-1]:=0;
  22. for i:=1 to N-1 do
  23. if (P[i]<P[i-1]) and (P[i]<P[i+1]) then valli[i]:=1;
  24.  
  25. ANS := 0;
  26.  
  27. (*leftLIS[i] stores the length of longest increasing subsequence ending at index i*)
  28. (*rightLIS[i] stores the length of longest decreasing subsequence starting at index i*)
  29.  
  30. for i:=0 to N-1 do begin leftLIS[i]:=1; rightLIS[i]:=1; scartato[i]:=0; end;
  31.  
  32. (*Calculate LIS from left to right for each position*)
  33.  
  34. for i := 1 to N-1 do
  35. for j:= 0 to i-1 do
  36. begin
  37. if (P[i] > P[j]) then leftLIS[i] := max(leftLIS[i], leftLIS[j] + 1);
  38. if (i>0) and (i<N-1) and (P[i]<P[i-1]) then scartato[i]:=1;
  39. end;
  40.  
  41. (* Calculate LIS from right to left (decreasing subsequence) for each position*)
  42.  
  43. for i := N - 2 downto 0 do
  44. for j := i + 1 to N-1 do
  45. if (P[i] > P[j]) then rightLIS[i] := max(rightLIS[i], rightLIS[j] + 1);
  46. if (i<N-1) and (i>0) and (P[i]<P[i+1]) then scartato[i]:=1;
  47.  
  48. (* Find the maximum length of mountain subsequence*)
  49. count:=0;
  50. for i:=0 to N-1 do if ((scartato[i]=1) and (valli[i]=1)) then count:=count+1;
  51. maxMountainLength := 0;
  52. for i := 0 to N-1 do
  53. (*A valid mountain peak must have at least one element on both sides*)
  54. (*leftLIS[i] > 1 ensures there's at least one element before peak*)
  55. (*rightLIS[i] > 1 ensures there's at least one element after peak*)
  56. if (leftLIS[i] >= 1) and (rightLIS[i] >= 1) then
  57. (*Total mountain length with peak at i Subtract 1 because peak is counted in both leftLIS and rightLIS*)
  58. maxMountainLength := max(maxMountainLength, leftLIS[i] + rightLIS[i] - 1);
  59. (* Minimum removals = total elements - maximum mountain length*)
  60. ANS:=max (N - maxMountainLength,N - maxMountainLength - count) ;
  61. WriteLn(ANS);
  62. end.
Success #stdin #stdout 0s 5324KB
stdin
5
0 3 4 2 1
stdout
0