@FanFeng The idea about this algorithm is to use the optimal value that has been calculated before to construct the new optimal for the current element.

The hash map simply stores the longest length in regard to each element stored as the key of the map.

The reason why you have to do "map.put(n - left, sum);" and "map.put(n + right, sum);" is that once you have constructed the longest length for the current element, you want to make sure the known boundary of the current element also gets updated.

For example: the input is [100,4,200,1,3,2], you will be able to calculate the length for element 2 (which is the last element in this array) and the result is 4.

For element 2, the left boundary's length is 1 and the right boundary's length is 2. So the boundary for element 2 based on previously calculated result is 0 -> 4.

So what happens if we do not update the boundary?

Let's add one more element (0) into this array to make the array [100,4,200,1,3,2,0]. If you do not update the left boundary of element 2, then the length associated with element 0 would be 0. So if your code then traverse to the last element of the new array, which is 0, you cannot get the new longest length 5.

Basically, you are always updating the maximum length in regard to the current element and its boundaries. Because within the boundaries, every element should refer to the known maximum length that's calculated previously.