LeetCode 3284: Sum of Consecutive Subarrays

Problem Description

Explanation:

Given an array of integers nums and an integer k, we need to find the sum of all subarrays of length k in the array.

To achieve this, we can use a sliding window approach. We first calculate the sum of the first k elements and store it. Then, we slide the window by removing the element at the beginning of the window and adding the element at the end of the window. We keep track of the sum of the current window and update the result accordingly. By doing this, we can calculate the sum of all subarrays of length k efficiently. Solution:

Solutions

public int[] sumOfConsecutiveSubarrays(int[] nums, int k) {
    int n = nums.length;
    int[] result = new int[n - k + 1];
    
    int sum = 0;
    for (int i = 0; i < k; i++) {
        sum += nums[i];
    }
    result[0] = sum;
    
    for (int i = k; i < n; i++) {
        sum += nums[i] - nums[i - k];
        result[i - k + 1] = sum;
    }
    
    return result;
}

Loading editor...