Optimized by keeping track of a max variable on each iteration