• + 0 comments

    You cannot directly sum each item in range because you will get a Time Exceeded Exception.

    Instead, use prefix sum technique:

    // Swift
    func arrayManipulation(n: Int, queries: [[Int]]) -> Int {
        // 1-indexed
        var operations: [Int] = Array(repeating: 0, count: n + 1)
    
        for query in queries {
            let a = query[0]
            let b = query[1]
            let k = query[2]
    
            operations[a - 1] += k
            operations[b] -= k
        }
        
        var maxValue = 0
        var currentSum = 0
        for value in operations {
            currentSum += value
            maxValue = max(maxValue, currentSum)
        }
        
        return maxValue
    }