303.Range Sum Query - Immutable

Tags: [dp], [preprocessing]

Link: https://leetcode.com/problems/range-sum-query-immutable/\#/description

Given an integer array nums, find the sum of the elements between indices i and j(i≤j), inclusive.

Example:

Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3

Note:

  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.

Solution: DP

class NumArray(object):

    def __init__(self, nums):
        """
        :type nums: List[int]
        """
        self.nums_is_empty = False
        if not nums:
            self.nums_is_empty = True
            return

        self.total = sum(nums)
        self.sum_left = [0 for _ in xrange(len(nums))]
        self.sum_right = [0 for _ in xrange(len(nums))]

        self.sum_left[0] = nums[0]
        for i in xrange(1, len(nums)):
            self.sum_left[i] = nums[i] + self.sum_left[i - 1]

        self.sum_right[-1] = nums[-1]
        for i in xrange(len(nums) - 2, -1, -1):
            self.sum_right[i] = nums[i] + self.sum_right[i + 1]

    def sumRange(self, i, j):
        """
        :type i: int
        :type j: int
        :rtype: int
        """
        if self.nums_is_empty:
            return 0

        if not (0 <= i <= j < len(self.sum_left)):
            raise ValueError('the input i and j are invalid')

        result = self.total
        if i - 1 >= 0:
            result -= self.sum_left[i - 1]
        if j + 1 < len(self.sum_right):
            result -= self.sum_right[j + 1]

        return result

# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j)

Note:

  • Time complexity of initialization = O(n), n is the number of elements of the given nums.
  • Time complexity of sumRange = O(1).

results matching ""

    No results matching ""