master
1<<-DOC
2You have an array of integers nums and an array queries, where queries[i] is a pair of indices (0-based).
3Find 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.
4Return that number modulo 10^9 + 7.
5
6Example
7
8For nums = [3, 0, -2, 6, -3, 2] and queries = [[0, 2], [2, 5], [0, 5]], the output should be
9sumInRange(nums, queries) = 10.
10
11The array of results for queries is [1, 3, 6], so the answer is 1 + 3 + 6 = 10.
12
13Input/Output
14
15[time limit] 4000ms (rb)
16[input] array.integer nums
17
18An array of integers.
19
20Guaranteed constraints:
211 ≤ nums.length ≤ 105,
22-1000 ≤ nums[i] ≤ 1000.
23
24[input] array.array.integer queries
25
26An array containing sets of integers that represent the indices to query in the nums array.
27
28Guaranteed constraints:
291 ≤ queries.length ≤ 3 · 105,
30queries[i].length = 2,
310 ≤ queries[i][j] ≤ nums.length - 1,
32queries[i][0] ≤ queries[i][1].
33
34[output] integer
35
36An integer that is the sum of all of the sums gotten from querying nums, taken modulo 109 + 7.
37DOC
38
39describe "sum_in_range" do
40 MODULO = (10 ** 9) + 7
41
42 def sum_in_range(numbers, queries)
43 queries.inject(0) do |memo, (x, y)|
44 memo + numbers[x..y].inject(0, &:+)
45 end % MODULO
46 end
47
48 def sum_in_range(numbers, queries)
49 sums = 0.upto(numbers.size - 1).inject([]) do |memo, n|
50 memo[n] = n == 0 ? numbers[n] : memo[n - 1] + numbers[n]
51 memo
52 end
53
54 queries.inject(0) do |memo, (x, y)|
55 memo += (x > 0) ? sums[y] - sums[x - 1] : sums[y]
56 end % ((10 ** 9) + 7)
57 end
58
59 [
60 { nums: [3, 0, -2, 6, -3, 2], queries: [[0,2], [2,5], [0,5]], x: 10 },
61 { nums: [-1000], queries: [[0,0]], x: 999999007 },
62 { nums: [34, 19, 21, 5, 1, 10, 26, 46, 33, 10], queries: [[3,7], [3,4], [3,7], [4,5], [0,5]], x: 283 },
63 { nums: [-4, -18, -22, -14, -33, -47, -29, -35, -50, -19], queries: [[2,9], [5,6], [1,2], [2,2], [4,5]], x: 999999540 },
64 { nums: [-23, -8, -52, -58, 93, -16, -26, 75, -77, 25, 90, -50, -31, 70, 53, -68, 96, 100, 69, 13], queries: [[0,4], [0,8], [7,7], [3,4], [2,3], [0,3], [8,8], [2,2], [5,7], [2,2]], x: 999999578 },
65 { nums: [-77, 54, -59, -94, -13, -78, -81, -38, -26, 17, -73, -88, 90, -42, -63, -36, 37, 25, -22, 4, 25, -86, -44, 88, 2, -47, -29, 71, 54, -42], queries: [[2,2], [4,7], [2,4], [0,2], [3,6], [6,6], [3,3], [2,7], [3,4], [3,3], [2,9], [0,1], [4,4], [2,3], [0,6], [4,4], [2,3], [0,5], [2,5], [4,5]], x: 999996808 },
66 { nums: [1000], queries: [[0,0]], x: 1000 },
67 ].each do |x|
68 it do
69 expect(sum_in_range(x[:nums], x[:queries])).to eql(x[:x])
70 end
71 end
72end