(* Collection of code snippets by Arne Vajhøj *)
(* (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) *)
program subset;

{$APPTYPE CONSOLE}

uses
  Windows, SysUtils;

type
  TIntArr = array of integer;

function find(input : TIntArr) : TIntArr;

var
  dim, i, j, maxix, ix : integer;
  res, seqlen, next : TIntArr;

begin
  dim := high(input) - low(input) + 1;
  SetLength(seqlen, dim);
  SetLength(next, dim);
  maxix := dim - 1;
  for i := dim - 1 downto 0 do begin
    seqlen[i] := 1;
    next[i] := -1;
    for j := i + 1 to dim - 1 do begin
      if input[low(input) + j] > input[low(input) + i] then begin
        if 1 + seqlen[j] > seqlen[i] then begin
          seqlen[i] := 1 + seqlen[j];
          next[i] := j;
        end;
      end;
    end;
    if seqlen[i] > seqlen[maxix] then maxix := i;
  end;
  SetLength(res, seqlen[maxix]);
  ix := maxix;
  for i := 0 to seqlen[maxix] - 1 do begin
    res[i] := input[low(input) + ix];
    ix := next[ix];
  end;
  find := res;
end;

var
  i, j, n, t1, t2 : integer;
  input, output : TIntArr;

begin
  SetLength(input, 15);
  input[0] := 16;
  input[1] := 6;
  input[2] := 3;
  input[3] := 4;
  input[4] := 5;
  input[5] := 21;
  input[6] := 22;
  input[7] := 7;
  input[8] := 9;
  input[9] := 10;
  input[10] := 11;
  input[11] := 12;
  input[12] := 13;
  input[13] := 14;
  input[14] := 15;
  output := find(input);
  for i := low(output) to high(output) do begin
    write(' ',output[i]);
  end;
  writeln;
  t1 := GetTickCount;
  for i:= 0 to 49999 do output := find(input);
  t2 := GetTickCount;
  writeln(t2-t1, ' milliseconds');
  SetLength(input, 50000);
  for i := 0 to 49999 do input[i] := random(1000000000);
  t1 := GetTickCount;
  output := find(input);
  t2 := GetTickCount;
  writeln((t2-t1) div 1000, ' seconds');
  for n := 10 to 50 do begin
    SetLength(input, n);
    t1 := GetTickCount;
    for j := 1 to 100 do begin
      for i := 0 to n-1 do input[i] := random(1000000000);
      output := find(input);
    end;
    t2 := GetTickCount;
    writeln(n, ' ', (t2-t1) div 100, ' milliseconds');
  end;
  readln;
end.
