暴力法
private int [] nums;
public static void main(String[] args) {
int [] nums = {-2, 0, 3, -5, 2, -1};
Demo2 demo2 =new Demo2(nums);
System.out.println(demo2.sumRange(0,5));
}
public Demo2(int[] nums) {
this.nums = nums;
}
public int sumRange(int i, int j) {//197ms
int sum = 0;
for (int k = i; k <=j ; k++) {
sum+=nums[k];
}
return sum;
}
动态规划
private int [] dp;
public static void main(String[] args) {
int [] nums = {-2, 0, 3, -5, 2, -1};
Demo1 demo2 =new Demo1(nums);
System.out.println(demo2.sumRange(0,2));
}
public Demo1(int[] nums) {
dp = new int[nums.length + 1];
for (int i = 0; i < nums.length; i++) {
dp[i + 1] = dp[i] + nums[i];
}
}
public int sumRange(int i, int j) {
return dp[j + 1] - dp[i];
}