I can solve this problem with a brute force naive solution, but need to optimize it for time. I'm not in school, but trying to learn fundamentals on my own.
I know I need to store the sum of the indices already counted so that I am not recounting ranges I've already covered. Like in the example below if I already summed [0,2] and [2, 5] I could just add those sums to get [0, 5] sum without iterating over array. But I don't know how to implement this.
Here is the description:
You have an array of integers nums and an array queries, where queries[i] is a pair of indices (0-based). Find the sum of the elements in nums from the indices at queries[i][0] to queries[i][1] (inclusive) for each query, then add all of the sums for all the queries together. Return that number modulo 10^9 + 7.
Example:
For nums = [3, 0, -2, 6, -3, 2] and queries = [[0, 2], [2, 5], [0, 5]], the output should be sumInRange(nums, queries) = 10.
The array of results for queries is [1, 3, 6], so the answer is 1 + 3 + 6 = 10.
My solution:
func sumInRange(nums: [Int], queries: [[Int]]) -> Int {
var sumArray = [Int]()
for q in queries {
var tempSum = 0
for i in q[0]...q[1] {
tempSum += nums[i]
}
sumArray += [tempSum]
}
let sum = sumArray.reduce(0, +)
let bigNumber = 1000000000 + 7
return sum > 0 ? sum % bigNumber : bigNumber + sum
}