let next_greater arr =
  let n = Array.length arr in
  let res = Array.make n (-1) in
  let stack = ref [] in
  for i = n - 1 downto 0 do
    while (match !stack with [] -> false | h :: _ -> h <= arr.(i)) do
      stack := List.tl !stack
    done;
    (match !stack with
     | [] -> res.(i) <- -1
     | h :: _ -> res.(i) <- h);
    stack := arr.(i) :: !stack
  done;
  res

;;

let r = next_greater [| 4; 5; 2; 25; 7; 8; 1; 30; 12 |] in
let sum = ref 0 in
for i = 0 to Array.length r - 1 do
  if r.(i) >= 0 then sum := !sum + r.(i)
done;
!sum
