data structures - How can I make this Algorithm more efficient? -
i've got algorithm produces 2d array containing sum of possible values. example, array [1,5,8,4,5], 2d array sums[1][3] should return sum of index 1-3 in original array (17). believe in terms of big o, efficiency o(n2). there way can make algorithm more efficient?
public static int[][] sum(int[] values){ int[][] sums = new int[values.length][values.length]; for(int x = 0; x < values.length; x++){ int total = 0; for(int y = x; y < values.length; y++) { total += values[y]; sums[x][y] = total; } } return sums; }
you can solve in o(n) time , space prefix-sum array:
array = [1, 5, 8, 4, 5] prefixes = [1, 6,14,18,23] sums(1,3) = prefixes[3] - prefixes[0] = 18 - 1 = 17
Comments
Post a Comment