Skip to content

4128. Weighted Range Sum Queries

DifficultyHard

Description

You are given an integer array nums of length n and a 2D integer array queries.

Process the queries in order:

  • [1, idxi, vali]: Set nums[idxi] to vali.
  • [2, li, ri]: Calculate the weighted sum of the subarray from li to ri (inclusive):
    nums[li] + 2 * nums[li + 1] + ... + (ri - li + 1) * nums[ri].

Return an integer array containing the results of all type 2 queries in order.

 

Example 1:

Input: nums = [1,2,3,4,5], queries = [[2,0,2],[1,2,6],[2,1,3],[2,3,4]]

Output: [14,26,14]

Explanation:

i queries[i] Action nums Result
0 [2, 0, 2] 1*1 + 2*2 + 3*3 = 14 [1, 2, 3, 4, 5] 14
1 [1, 2, 6] Update nums[2] = 6 [1, 2, 6, 4, 5] -
2 [2, 1, 3] 1*2 + 2*6 + 3*4 = 26 [1, 2, 6, 4, 5] 26
3 [2, 3, 4] 1*4 + 2*5 = 14 [1, 2, 6, 4, 5] 14

Thus, answer = [14, 26, 14].

Example 2:

Input: nums = [10,20], queries = [[1,0,5],[1,1,15]]

Output: []

Explanation:

i queries[i] Action nums Result
0 [1, 0, 5] Update nums[0] = 5 [5, 20] -
1 [1, 1, 15] Update nums[1] = 15 [5, 15] -

Thus, answer = [].

Example 3:

Input: nums = [2,3,3,6], queries = [[2,0,3],[2,3,3],[1,3,4],[2,0,3],[2,1,3]]

Output: [41,6,33,21]

Explanation:

i queries[i] Action nums Result
0 [2, 0, 3] 1*2 + 2*3 + 3*3 + 4*6 = 41 [2, 3, 3, 6] 41
1 [2, 3, 3] 1*6 = 6 [2, 3, 3, 6] 6
2 [1, 3, 4] Update nums[3] = 4 [2, 3, 3, 4] -
3 [2, 0, 3] 1*2 + 2*3 + 3*3 + 4*4 = 33 [2, 3, 3, 4] 33
4 [2, 1, 3] 1*3 + 2*3 + 3*4 = 21 [2, 3, 3, 4] 21

Thus, answer = [41, 6, 33, 21].

 

Constraints:

  • 1 <= n == nums.length <= 105
  • 1 <= nums[i] <= 105
  • 1 <= queries.length <= 105
  • queries[i] = [1, idxi, vali] or queries[i] = [2, li, ri]
  • 0 <= idxi <= n - 1
  • 1 <= vali <= 105
  • 0 <= li <= ri <= n - 1

Solutions

Solution 1

1

1

1

1

Comments