more space efficient implementation of DTW algorithm