LeetCode 1714: Sum Of Special Evenly-Spaced Elements In Array

Problem Description

Explanation:

Given an array nums and two integers a and b, we are required to calculate the sum of the special evenly-spaced elements in the array. Special evenly-spaced elements are elements that are located at indices i, i+a, i+2a, ..., i+ka for some integer k such that i+ka <= n-1 where n is the size of the array.

To solve this problem efficiently, we can use the concept of prefix sums. We can pre-calculate the prefix sum of the array nums to quickly compute the sum of any subarray. By iterating over all possible starting indices i, we can calculate the sum of special evenly-spaced elements using the prefix sum array.

: :

Solutions

class Solution {
    public int[] solve(int[] nums, int a, int b) {
        int n = nums.length;
        int[] prefixSum = new int[n];
        prefixSum[0] = nums[0];
        for (int i = 1; i < n; i++) {
            prefixSum[i] = prefixSum[i - 1] + nums[i];
        }
        
        int result = 0;
        for (int i = 0; i < n; i++) {
            for (int k = 0; i + k * a + b < n; k++) {
                result += prefixSum[i + k * a + b] - (i > 0 ? prefixSum[i - 1] : 0);
            }
        }
        
        return result;
    }
}

Loading editor...