Skip to content
LC-3427 Easy LeetCode

3427. Sum of Variable Length Subarrays

Read the full problem statement on LeetCode.
Difficulty: easy Acceptance: 85% Topics: Array, Prefix Sum
View full problem on LeetCode
Reference solution (spoiler · python)
# Time:  O(n)
# Space: O(n)

# difference array
class Solution(object):
    def subarraySum(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        diff = [0]*(len(nums)+1)
        for i, x in enumerate(nums):
            diff[max(i-x, 0)] += 1
            diff[i+1] -= 1
        for i in xrange(len(nums)):
            diff[i+1] += diff[i]
        return sum(nums[i]*diff[i] for i in xrange(len(nums)))

Solution from kamyu104/LeetCode-Solutions · MIT