import Foundation
func maxLengthSubarrayEqualsToK(_ arr: [Int], _ K: Int) -> Int {
var map = [Int: Int]() // To store cumulative sum and its index
var maxLength = 0
var cumulativeSum = 0
for i in 0..<arr.count {
cumulativeSum += arr[i]
// If the cumulative sum equals K, update maxLength
if cumulativeSum == K {
maxLength = i + 1
}
// If (cumulativeSum - K) exists in the map, update maxLength
if let prevIndex = map[cumulativeSum - K] {
maxLength = max(maxLength, i - prevIndex)
}
// Store the cumulative sum in the map if not already present
if map[cumulativeSum] == nil {
map[cumulativeSum] = i
}
}
return maxLength
}
let arr = [1, -1, 5, -2, -3, 2, 3, 3]
let K = 3
// 1, -1, 5, -2 = 3 (length 4)
// 5, -2 = 3 (length 2)
// -2, -3, 2, 3, 3 = 3 (length 5)
print(maxLengthSubarrayEqualsToK(arr, K))
/*
run:
5
*/