Skip to content

3427. Sum of Variable Length Subarrays

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int subarraySum(vector<int>& nums) {
    const int n = nums.size();
    int ans = 0;
    vector<int> prefix(n + 1);

    partial_sum(nums.begin(), nums.end(), prefix.begin() + 1);

    for (int i = 0; i < n; ++i)
      ans += prefix[i + 1] - prefix[max(0, i - nums[i])];

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int subarraySum(int[] nums) {
    final int n = nums.length;
    int ans = 0;
    int[] prefix = new int[n + 1];

    for (int i = 0; i < n; ++i)
      prefix[i + 1] = prefix[i] + nums[i];

    for (int i = 0; i < n; ++i)
      ans += prefix[i + 1] - prefix[Math.max(0, i - nums[i])];

    return ans;
  }
}
1
2
3
4
5
class Solution:
  def subarraySum(self, nums: list[int]) -> int:
    prefix = list(itertools.accumulate(nums, initial=0))
    return sum(prefix[i + 1] - prefix[max(0, i - num)]
               for i, num in enumerate((nums)))