function m = dyna(v)

[r n] = size(v);
a = inf(3, n);
a(1,1) = max([0; v(:,1)]);
a(2,1) = max([0; v(2,1)]);
a(3,1) = max([0; v(1,1)]);
m = f1(n);
a

   function b = f1(n)
     if a(1,n-1) ~= inf
        x = a(1,n-1);
     else
        x = f1(n-1);
     end
     if a(2,n-1) ~= inf
        y = v(1,n)+a(2,n-1);
     else
        y = v(1,n)+f2(n-1);
     end
     if a(3,n-1) ~= inf
        z = v(2,n)+a(3,n-1);
     else
        z = v(2,n)+f3(n-1);
     end
     b = max([x, y, z]);
     a(1,n) = b;
   end

   function b = f2(n)
      if a(1,n-1) ~= inf
         x = a(1,n-1);
      else
         x = f1(n-1);
      end
      if a(3,n-1) ~= inf
         z = v(2,n)+a(3,n-1);
      else
         z = v(2,n)+f3(n-1);
      end
      b = max([x, z]);
      a(2,n) = b;
   end

   function b = f3(n)
      if a(1,n-1) ~= inf
         x = a(1,n-1);
      else
         x = f1(n-1);
      end
      if a(2,n-1) ~= inf
         y = v(1,n)+a(2,n-1);
      else
         y = v(1,n)+f2(n-1);
      end
      b = max([x, y]);
      a(3,n) = b;
   end
end

