easyArraysPattern: Math

WeightedSumCalculation Solution

Problem Statement

You are given two arrays of integers, `weights` and `values`, of the same length. Calculate the total weighted sum by summing the product of each weight and its corresponding value, and return the total weighted sum.

Examples

Example 1:
Input:[[1,2,3],[4,5,6]]
Output:32
Explanation: The weighted sum is calculated as (1*4) + (2*5) + (3*6) = 4 + 10 + 18 = 32
Example 2:
Input:[[-1,0,1],[1,2,3]]
Output:2
Explanation: The weighted sum is calculated as (-1*1) + (0*2) + (1*3) = -1 + 0 + 3 = 2
Example 3:
Input:[[2,2,2],[2,2,2]]
Output:12
Explanation: The weighted sum is calculated as (2*2) + (2*2) + (2*2) = 4 + 4 + 4 = 12

Constraints

  • 1 <= weights.length <= 1000
  • weights.length == values.length
  • -1000 <= weights[i] <= 1000
  • -1000 <= values[i] <= 1000
Time: O(n) Space: O(1)
The optimized approach also uses a loop to iterate over the weights and values arrays, but it avoids unnecessary calculations by using a single loop to calculate the total weighted sum.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

def weighted_sum_calculation(weights, values): return sum(w * v for w, v in zip(weights, values))