function [V,indxOptSaving,gridK] = lc(Kmax,nK)
  % VECTORIZED VERSION of lifecycle.m
  % parameters:
  beta = 0.98;
  r = 0.015;
  y = [ones(40,1);zeros(20,1)];
  T = length(y);

  Kmin = 0;  % no borrowing allowed
  % grid of possible capital states:
  gridK = linspace(Kmin,Kmax,nK)';

  V = NaN(nK,T+1);  % value function
  V(:,T+1) = 0;   % no value of capital after death (no bequest motive)
  indxOptSaving = NaN(nK,T);
  for t=T:-1:1  % iterate backwards in time
    fprintf(1,'now solving period %d\n',t);
    for i=1:nK   % optimize at each grid point
      Kbeg = gridK(i);

      Kend = gridK; % try all levels of saving
      c = (1+r)*Kbeg + y(t) - Kend; % all consumption levels
      Vtry = util(c) + beta*V(:,t+1);

      [V(i,t),indxOptSaving(i,t)] = max(Vtry);
    end
  end

end

function u = util(c);
  u = -Inf(size(c));
  iPos = c>0;
  u(iPos) = log(c(iPos));
end

