Next Greatest Element Algorithm