LeetCode 303. Range Sum Query - Immutable

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

classic DP problem.

dp[i] is the sum from 0 to i exclusively
very easy, just be more careful.

class NumArray {
    
    
    private int[] sum;
    
    public NumArray(int[] nums) {
        int m = nums.length;
        sum = new int[m+1];
        sum[0] = 0;
        for (int i = 1; i <= m; i++) {
            sum[i] = sum[i-1] + nums[i-1];
        }
    }
    
    public int sumRange(int i, int j) {
        return sum[j+1] - sum[i];
    }

    
}

posted @ 2020-11-22 03:10  EvanMeetTheWorld  阅读(20)  评论(0)    收藏  举报