How to find maximum sum of a subarray of size k – Sliding window swift

[Question]: Find maximum sum of a subarray of size k example [9,1,3,2,6,1,5,9], k: 4 = output: 21 (6+1+5+9)
Solution: with sliding window we can achieve. first we take sum of first k elements further move elements by 1 window size & add the latest var & remove last var.

func findMaxSubArray(arr: [Int], k: Int) ->Int {
    let size = arr.count
    if k > size { return -1 }
    var maxSum = 0
    for i in 0..<k {
        maxSum += arr[i]
    }
    var thisSum = maxSum
    for i in k..<size {
        thisSum += arr[i] - arr[i-k]
// Add the difrence value from last to first
        maxSum = max(maxSum, thisSum)
    }
    return maxSum
    
}
print(findMaxSubArray(arr: [9,1,3,2,6,1,5,9], k: 4))

Leave a Comment

Your email address will not be published. Required fields are marked *