Motivated by work of ErdH{o}s, Ota determined the maximum size $g(n,k)$ of a $k$-connected nonhamiltonian graph of order $n$ in 1995. But for some pairs $n,k,$ the maximum size is not attained by a graph of connectivity $k.$ For example, $g(15,3)=77$ is attained by a unique graph of connectivity $7,$ not $3.$ In this paper we obtain more precise information by determining the maximum size of a nonhamiltonian graph of order $n$ and connectivity $k,$ and determining the extremal graphs. Consequently we solve the corresponding problem for nontraceable graphs.