fork download
  1. program mountain;
  2. Uses Math;
  3. const
  4. MAXN = 100005;
  5.  
  6. var
  7. ANS, N, i, j, maxMountainLength : LongInt;
  8. P, leftLIS, rightLIS, rimosso : 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. ANS := 0;
  22.  
  23. (*leftLIS[i] stores the length of longest increasing subsequence ending at index i*)
  24. (*rightLIS[i] stores the length of longest decreasing subsequence starting at index i*)
  25.  
  26. for i:=0 to N-1 do begin leftLIS[i]:=1; rightLIS[i]:=1; rimosso[i]:=0; end;
  27.  
  28. (*Calculate LIS from left to right for each position*)
  29. for i:=1 to N-2 do if (P[i]<P[i-1]) and (P[i]<P[i+1]) then rimosso[i]:=1;
  30. for i := 1 to N-1 do
  31. if (rimosso[i]=0) then
  32. for j:= 0 to i-1 do
  33. begin
  34. if (rimosso[j]=0) and (P[i] > P[j]) then leftLIS[i] := max(leftLIS[i], leftLIS[j] + 1);
  35. end;
  36.  
  37. (* Calculate LIS from right to left (decreasing subsequence) for each position*)
  38.  
  39. for i := N - 2 downto 0 do
  40. if (rimosso[i]=0) then
  41. for j := i + 1 to N-1 do
  42. begin
  43. if (rimosso[j]=0) and (P[i] > P[j]) then rightLIS[i] := max(rightLIS[i], rightLIS[j] + 1);
  44. end;
  45.  
  46. (* Find the maximum length of mountain subsequence*)
  47. maxMountainLength := 0;
  48. for i := 0 to N-1 do
  49. (*A valid mountain peak must have at least one element on both sides*)
  50. (*leftLIS[i] > 1 ensures there's at least one element before peak*)
  51. (*rightLIS[i] > 1 ensures there's at least one element after peak*)
  52. if (leftLIS[i] >= 1) and (rightLIS[i] >= 1) then
  53. (*Total mountain length with peak at i Subtract 1 because peak is counted in both leftLIS and rightLIS*)
  54. maxMountainLength := max(maxMountainLength, leftLIS[i] + rightLIS[i] - 1);
  55. (* Minimum removals = total elements - maximum mountain length*)
  56. ANS:= N - maxMountainLength;
  57. WriteLn(ans);
  58. end.
Success #stdin #stdout 0s 5320KB
stdin
8
0 1 6 5 4 3 2 7
stdout
2