1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| public class Prefix_num_sum { public static void main(String[] args) { int[] arr1 = new int[]{1,3,2,2,3,4,3,2,5}; initSumOfRangeL_R(arr1); System.out.println(getSumOfRangeL_R(0,2));
int[] arr2 = new int[]{1,3,2,2,3,4,3,2,5}; initPreSum(arr2); System.out.println(getPreSum(arr2,0,2));
}
public static int simpleSumOfRangeL_R(int[] arr, int L , int R){ int result = 0; for (int i = 0; i < arr.length; i++) { if (i >= L && i <=R) { result += arr[i]; } } return result; }
private static int[][] help ; public static void initSumOfRangeL_R(int[] arr) { int N = arr.length; help = new int[N][N]; for (int hor = 0; hor < N; hor++) { for (int ver = 0; ver < N; ver++) { if (hor == ver) { help[hor][ver] = arr[hor]; } else if(hor > ver & hor > 0) { help[hor][ver] = help[hor - 1][ver] + arr[hor]; } } } } public static int getSumOfRangeL_R(int L, int R) { if (L > R) return 0; return help[R][L]; }
private static int[] preSumHelp; public static void initPreSum(int[] arr) { int N = arr.length - 1; preSumHelp = new int[N]; preSumHelp[0] = arr[0]; for (int i = 1; i < N; i++) { preSumHelp[i] = preSumHelp[i-1] + arr[i] ; } } public static int getPreSum(int[] arr, int L ,int R) { if (L > R) return 0; return L == 0 ? preSumHelp[R] : preSumHelp[R] - preSumHelp[L-1]; } }
|