let lcs s1 s2 =
  let m = String.length s1 in
  let n = String.length s2 in
  let prev = Array.make (n + 1) 0 in
  let curr = Array.make (n + 1) 0 in
  for i = 1 to m do
    for j = 1 to n do
      if s1.[i - 1] = s2.[j - 1] then
        curr.(j) <- prev.(j - 1) + 1
      else if prev.(j) >= curr.(j - 1) then
        curr.(j) <- prev.(j)
      else
        curr.(j) <- curr.(j - 1)
    done;
    for j = 0 to n do
      prev.(j) <- curr.(j)
    done
  done;
  prev.(n)

;;

lcs "ABCBDAB" "BDCAB"
