package advanced.design.lc303_rangesumqueryimmutable;

/**
 * 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: You may assume that the array does not change. There are many calls to sumRange function.
 */
public class NumArray {

    // sum[i] = sum of [0,i]
    private int[] sum;

    public NumArray(int[] nums) {
        if (nums.length == 0) {
            sum = new int[0];
            return;
        }

        sum = new int[nums.length];
        sum[0] = nums[0];
        for (int i = 1; i < nums.length; i++) {
            sum[i] = sum[i - 1] + nums[i];
        }
    }

    public int sumRange(int i, int j) {
        if (i < 0 || j >= sum.length) {
            return 0;
        }
        return sum[j] - (i > 0 ? sum[i - 1] : 0);
    }

}

@@ -925,10 +925,562 @@
 %0A    %7D%0A%0A
+    // My 2AC%0A    // sum%5Bi%5D = sum of %5B0,i%5D%0A    //private int%5B%5D sum;%0A%0A    public void NumArray2(int%5B%5D nums) %7B%0A        sum = new int%5Bnums.length%5D;%0A        if (nums.length %3E 0) %7B%0A            sum%5B0%5D = nums%5B0%5D;%0A            for (int i = 1; i %3C nums.length; i++) %7B%0A                sum%5Bi%5D = sum%5Bi - 1%5D + nums%5Bi%5D;%0A            %7D%0A        %7D%0A    %7D%0A%0A    public int sumRange2(int i, int j) %7B%0A        if (i %3C 0 %7C%7C i %3E sum.length - 1 %7C%7C j %3C 0 %7C%7C j %3E sum.length - 1 %7C%7C i %3E j) %7B%0A            return 0;%0A        %7D%0A        return i == 0 ? sum%5Bj%5D : sum%5Bj%5D - sum%5Bi - 1%5D;%0A    %7D%0A
 %7D%0A

leetcode-303 range sum query immutable