A potential approach to address this issue is by utilizing Hashing. Below is a Python implementation: Let’s assume that arr represents our array of integers and targetSum denotes the specified sum. def maxLengthSubArray ( arr , targetSum ) : # create an empty dictionary hashMap = dict ( ) # to handle the case when the sub-array with given sum starts from index 0 hashMap [ 0 ] = - 1 # initialize the sum to 0 and maxLen to 0 sumOfElem , maxLen , end_index = 0 , 0 , - 1 # traverse the given array for i in range ( len ( arr ) ) : sumOfElem += arr [ i ] if sumOfElem not in hashMap : hashMap [ sumOfElem ] = i if ( sumOfElem - targetSum ) in hashMap and maxLen < i - hashMap [ sumOfElem - targetSum ] : maxLen = i - hashMap [ sumOfElem - targetSum ] end_index = i if end_index != - 1 : return arr [ end_index - maxLen + 1 : end_index + 1 ] else : return [ ] print ( maxLengthSubArray ( [ 10 , 5 , 2 , 7 , 2 , 5 , 6 , 8 ] , 14 ) ) In this solution, we employ a dictionary or hashmap to track the cumulative sum, sumOfElem , at each point along with its corresponding index, i . The length of the subarray is updated whenever we encounter a sum of elements that matches the targetSum .