[LeetCode] Sum of Variable Length Subarrays

3427. Sum of Variable Length Subarrays

You are given an integer array nums of size n. For each index i where 0 <= i < n, define a subarray nums[start ... i] where start = max(0, i - nums[i]).

Return the total sum of all elements from the subarray defined for each index in the array.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int subarraySum(vector<int>& nums) {
int res = 0;
for(int i = 0; i < nums.size(); i++) {
for(int j = max(0, i - nums[i]); j <= i; j++) res += nums[j];
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2025/01/19/PS/LeetCode/sum-of-variable-length-subarrays/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.