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